c# - 获取用户输入、成分和价格,并返回最便宜和最昂贵的
问题描述
我对 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();
}
}
}
解决方案
在面向对象编程中,我们将一切都视为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; }
}
并完全随意提出有关它的问题。祝你好运
推荐阅读
- excel - 使用自定义公式的 Excel 数据约束错误
- exiftool - 在 exiftool -if 条件下使用变量
- php - 如何安装和配置 PHPmailer?
- mongodb - 将 MongoDB 函数 foreach 转换为 mgo (Golang) 函数
- python - 我可以通过 mmap 增量构建文件吗?
- android - volley android 我的代码中的列表大小返回零
- linux - 创建的文件何时对 ext4 中的其他进程可见?
- sql-server - 更新时 SSIS 锁定表
- android - 如何在 Kotlin 中创建具体类型的对象
- sql - sql 剥离 http 和 https