【问题标题】:Calculate average grades, excluding the entered values that are the lowest and greatest计算平均成绩,不包括输入的最低和最高值
【发布时间】:2020-04-02 19:50:19
【问题描述】:

任务是允许用户输入 0 到 100 之间的值。如果用户输入 -99,程序应该停止。一旦程序退出,必须计算平均值。但是,平均值应包括所有输入的值,输入的最小值(最小值)和输入的最大值(最大值)除外。我写了一个相当好看的代码,但是它抛出了一个IndexOutOfRangeException

代码如下:

class Program
{
    static void Main(string[] args)
    {
        DisplayApp();

        Calculate();
    }

    static void DisplayApp()
    {
        Console.WriteLine("Grade Calculator: ");

        Console.WriteLine();
    }

    static double Calculate()
    {
        Console.WriteLine("Enter grades (-99 to exit): ");
        string input = Console.ReadLine();

        int[] array1 = new int[] { };

        int iInput = int.Parse(input);

        int min = 100;
        int max = 0;

        int i = 0;

        int sum = 0;
        double average = 0;

        while(iInput != 99)
        {
            if(iInput < min)
            {
                array1[i] = min;
            }
            else if(iInput > max)
            {
                array1[i] = max;
            }

            sum += iInput - (min + max);

            i++;
        }

        average = (double)sum / i;

        return average;
    }
}

您认为为了使该程序能够正常运行,可以改进哪些方面?

【问题讨论】:

  • int[] array1 = new int[] { }; 创建一个大小为零的空数组。数组大小需要在创建时知道。对于动态数据,您可以使用List
  • while(iInput != 99) 应该是-99,不是吗... while 循环中应该有ReadLine...

标签: c# exception average


【解决方案1】:

正如我在 cmets 中提到的,您创建了一个大小为零的数组。我不明白为什么你需要一个数组,因为你只是对值求和:

static double Calculate()
{
    Console.WriteLine("Enter grades (-99 to exit): ");

    int min = Int32.MaxValue;
    int max = Int32.MinValue;

    int sum = 0;
    int i = 0;

    while (true)
    {
        // TODO: Change to TryParse and handle input errors.
        int iInput = int.Parse(Console.ReadLine());
        if (iInput == -99) break;

        if (iInput > 0 && iInput < 100) {
            if (iInput < min)
            {
                min = iInput;
            }
            if (iInput > max)
            {
                max = iInput;
            }
            sum += iInput;
            i += 1;
        }
    }

    // TODO: Ensure no division by zero
    return (double)(sum - max - min) / (i - 2);
}

【讨论】:

  • @Rahul 不,它设置为MinValue,因此用户输入的任何值都将大于(或等于)它,并且将设置max
  • @zaimoff 我忘了移动Console.ReadLine()。固定。
  • 还是不行,谢谢你的帮助。
  • 你能解释一下“不起作用”吗?对我来说测试没问题:ideone.com/YznK3g
  • 成功了,抱歉。我搞砸了一行代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 2019-10-08
  • 1970-01-01
相关资源
最近更新 更多