我对C#完全陌生,遇到了一个我找不到解决方案的问题。
任务是为一道菜写下三种配料,然后给出它们的价格。然后,程序是找到最便宜和最昂贵的原料,并返回一条信息,说:
“你选择了第一种原料,价格最便宜”
“你选择了第二种原料,价格最贵”
我下面写的代码只显示没有相关成分的价格。有人知道怎么解决这个问题吗?
谢谢您抽时间见我!
static void Main(string[] args)
{
int counter = 0;
int price = 0;
int largest = 0;
int lowest = 0;
string ingredient;
for (counter = 0; counter < 3; counter++)
{
Console.WriteLine("Please select an ingredient");
ingredient = Console.ReadLine();
}
for (counter = 0; counter < 3; counter++)
{
Console.WriteLine("What is the price for it?");
price = Convert.ToInt32(Console.ReadLine());
if (counter == 0)
{
largest = price;
}
else
{
if (price > largest)
largest = price;
}
if (counter == 0)
{
lowest = price;
}
else
{
if (price < lowest)
lowest = price;
}
}
Console.WriteLine("The most expensive ingredient costs {0} $", largest);
Console.WriteLine("The cheapest ingredient costs {0} $", lowest);
Console.ReadLine();
}
}}
发布于 2020-02-05 07:15:45
在面向对象的编程中,我们把一切都看作是object.在您的场景中,您必须将ingredient看作具有Name和Price两个属性的对象。这样,对商业的理解就变得非常简单了。我重写了你的例子。
试试下面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var ingredients = new List<Ingredient>();
Console.WriteLine("Please enter count of ingredient:");
var countOfIngredient = int.Parse(Console.ReadLine());
for (var i = 0; i < countOfIngredient; i++)
{
Console.WriteLine("-----------------------------------------");
Console.WriteLine($"Please enter name of ingredient-{i}:");
var name = Console.ReadLine();
Console.WriteLine($"Please enter price of ingredient-{i}:");
var price= double.Parse(Console.ReadLine());
ingredients.Add(new Ingredient { Name = name, Price = price });
}
var cheapestIngredient = ingredients.OrderBy(i => i.Price).First();
var mostExpensiveIngredient= ingredients.OrderByDescending(i => i.Price).First();
Console.WriteLine("-----------------------------------------");
Console.WriteLine("-----------------------------------------");
Console.WriteLine($"The most expensive ingredient is {mostExpensiveIngredient.Name} with price of {mostExpensiveIngredient.Price} $");
Console.WriteLine($"The cheapest ingredient is {cheapestIngredient.Name} with price of {cheapestIngredient.Price} $");
Console.ReadLine();
}
}
class Ingredient
{
public string Name { get; set; }
public double Price { get; set; }
}完全可以自由地问问题。祝好运
https://stackoverflow.com/questions/60070374
复制相似问题