如何编写一个能够找到List中最大和最小分数的程序?
Console.WriteLine("How many fractions to comapre?");
string nic = Console.ReadLine();
int amount = int.Parse(nic);
double min = 0; double max = 0;
for (int i = 0; i < amount; i++)
{
Console.WriteLine("Enter fraction to compare. WRITE AS IMPROPER FRCATION");
string str = Console.ReadLine();
string[] each = str.Split('/');
List<double> eachDoub = new List<double> { };
foreach (string hit in each)
{
eachDoub.Add(double.Parse(hit));
}
List<double> finals = new List<double> { };
foreach (double hit in eachDoub)
{
finals.Add(eachDoub[0] / eachDoub[1]);
}
max = finals.Max();
min = finals.Min();
}
Console.WriteLine("The maximum is {0} and the minimum is {1}.", max, min);
Console.ReadLine();
输入:
comapre有多少分数? 3
输入分数
4/1
输入分数
3/1
当我运行此程序时,它无法正常工作,它只会打印为最小值和最大值输入的最后一个值。我该如何解决这个问题?
答案 0 :(得分:4)
只需移动此行
List<double> finals = new List<double> { };
离开循环。
为什么呢?因为当你在循环中拥有它时它不会跟踪所有值,它会“重置”每个相互关系
答案 1 :(得分:2)
您只需要在for
之外声明决赛列表,也可以在外面进行计算,因为当只需要一个时,不要调用Max()
和Min()
方法三次。在这种情况下,只有3次迭代,差异不会有意义,但作为一种良好的编码实践,你应该在循环外计算这些值。
Console.WriteLine("How many fractions to comapre?");
string nic = Console.ReadLine();
int amount = int.Parse(nic);
double min = 0; double max = 0;
List<double> finals = new List<double> { };
for (int i = 0; i < amount; i++)
{
Console.WriteLine("Enter fraction to compare. WRITE AS IMPROPER FRCATION");
string str = Console.ReadLine();
string[] each = str.Split('/');
List<double> eachDoub = new List<double> { };
foreach (string hit in each)
{
eachDoub.Add(double.Parse(hit));
}
foreach (double hit in eachDoub)
{
finals.Add(eachDoub[0] / eachDoub[1]);
}
}
max = finals.Max();
min = finals.Min();
Console.WriteLine("The maximum is {0} and the minimum is {1}.", max, min);
Console.ReadLine();
答案 2 :(得分:1)
这个循环看起来不对 - 永远不会使用迭代变量。
foreach (double hit in eachDoub)
{
finals.Add(eachDoub[0] / eachDoub[1]);
}