【问题标题】:Outputting averages from arrays C# based upon class average on a test根据测试中的类平均值从数组 C# 输出平均值
【发布时间】:2021-12-02 09:15:03
【问题描述】:

我正在尝试使用使用数组的程序在测试中输出整体班级平均值。该计划的目的是为一个 12 名学生的班级。当我尝试输入我需要的所有数据时,我没有得到整个班级的平均值。问题显然在于普通计算器本身,但鉴于我是初学者,我几乎不知道如何解决它。任何帮助,将不胜感激。重申一下,我正在寻找一个解决方案,以解决如何修复我的平均计算器以将班级平均水平作为一个整体。我在下面输入了我的代码。我希望我已经具体了。

string[] studentnames = new string[12];
        int[] testscore = new int[12];

        int i;
        int index;
        double average;
        int total = 0;

        //title

        Console.Write("\n\nStudent lists:\n");

        Console.Write("******************\n");

        //asks user to input names

        Console.Write("Enter student names:\n");

        for (i = 1; i < 12; i++)

        {

            Console.Write("Student name {0} : ", i);

            studentnames[i] = (Console.ReadLine());

            //asks user to enter student's test score

            Console.Write("Please enter their test score: ");

            testscore[i] = Convert.ToInt32(Console.ReadLine());

        }

        //outputs all values user has entered

        Console.WriteLine("\nStudent marks: ");

        for (i = 1; i < 12; i++)

        {

            Console.WriteLine("Name: ");

            Console.WriteLine("{0} ", studentnames[i]);

            Console.WriteLine("Test score: ");

            Console.WriteLine("{0} ", testscore[i]);

        }

        for (index = 1; index < 12; index++)
        {
            total = total + testscore[index];
            average = total / 12;

            Console.WriteLine("The class average was: " + average);
        }
        Console.ReadKey();

【问题讨论】:

    标签: c# arrays average


    【解决方案1】:

    除以总数需要在for循环之后。

    这个:

    for (index = 1; index < 12; index++)
    {
        total = total + testscore[index];
        average = total / 12;
    
        Console.WriteLine("The class average was: " + average);
    }
    

    需要成为:

    for (index = 1; index < 12; index++)
    {
        total = total + testscore[index];
    }
    average = ((double)total) / 12;
    Console.WriteLine("The class average was: " + average);
    

    另一个问题:for 循环从索引 1 开始。C# 使用基于 0 的索引。我假设您正在尝试计算 12 名学生的平均值,而不是 11 名。

    另外,看在上帝的份上,请停止写号码12。如果您绝对必须对其进行硬编码,请使用常量。

    编辑:我已经更新了我的答案以说明 flydog 的评论

    【讨论】:

    • @yeok:另外,如果你希望你的平均值是 double,不要将两个整数相除 - 它会得到一个整数(例如,如果你的总数是 825,当你将 825 除以 12,得到 68,而不是 68.75)。将平均计算改为average = (double) total / 12;由于股息是双倍的,因此结果将是双倍的。或者,您可以将 total 声明为 double 开头:double total = 0.0;
    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2021-12-22
    • 2021-06-23
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多