1

如何编写一个程序来查找 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();

输入:要比较多少分数?3
输入分数
4/1 输入分数
3/1

当我运行这个程序时,它不能正常工作,它只会打印为最小值和最大值输入的最后一个值。我怎样才能解决这个问题?

4

3 回答 3

4

移动这条线

 List<double> finals = new List<double> { };

跳出循环。

为什么?因为当您将它放在循环中时,它不会跟踪所有值,它会在每个相互关系上“重置”

于 2013-10-12T22:57:59.220 回答
2

你只需要在外部声明决赛列表,for并且在外部也进行计算,因为在只需要一个的情况下不会调用 3 次Max()and方法。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();
于 2013-10-12T22:58:18.850 回答
1

这个循环看起来不对——迭代变量从未被使用过。

    foreach (double hit in eachDoub)
    {
        finals.Add(eachDoub[0] / eachDoub[1]);
    }
于 2013-10-12T23:03:45.723 回答