首页 > 解决方案 > 使用 for 循环创建平均测试分数

问题描述

我正在尝试使用 for 循环计算出最多 4 个测试分数的测试分数。似乎我要超过 4 而不是停下来,并且不确定我做错了什么,因为它没有显示我的平均值。请指教:

        Console.WriteLine("Please enter your first test score");

        //variables
        double testScore = double.Parse(Console.ReadLine());
        double average = 0;

        for (int count = 0; count <= 4; count++) // Start the count from 0-4
        {
            //get the total
            average = average + testScore;

            Console.WriteLine("Please enter your other test score");
            testScore = double.Parse(Console.ReadLine());

            //Calculate and display 
            Console.WriteLine("The average of your test score is :", average / count);
        }


    }

标签: c#for-loop

解决方案


如果我理解正确,你需要一个小于号不小于或等于

for (int count = 0; count < 4; count++)

原因是你从 0 开始,即循环迭代0,1,2,3,4

或者(并且因为)您使用除法计数,您实际上应该从 1 开始

for (int count = 1; count <= 4; count++)

最后,您应该始终检查用户输入是否有肮脏的小手指

while(!double.TryParse(Console.ReadLine(),out testScore))
    Console.WriteLine("You had one job!);

public static bool TryParse (string s, out double result);

将数字的字符串表示形式转换为其等效的双精度浮点数。返回值指示转换是成功还是失败。


完整示例

double sum = 0;

for (int count = 0; count <= 4; count++) // Start the count from 0-4
{

    Console.WriteLine("Please enter your other test score");
    while(!double.TryParse(Console.ReadLine(),out testScore))
        Console.WriteLine("You had one job!);

    sum += testScore;

    //Calculate and display 
    Console.WriteLine($"The average of your test score is : {(sum / (double)count):N2}");
}

推荐阅读