使用While循环测试分数的平均值

时间:2018-09-28 03:04:14

标签: c# while-loop

我无法弄清楚为什么我的代码不断循环返回,而不是在输入0后不给我平均值。请告知:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter your first test score");

        //variables
        double testScore = double.Parse(Console.ReadLine()); //changing the number into a string
        double average = 0;
        int counter = 1;


        while (testScore != 0)
        {
            average += testScore; 
            counter++;

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

        }

        Console.WriteLine("The average of your test score is : {0}", average/counter); //displaying the average

    }
}

}

2 个答案:

答案 0 :(得分:2)

您可能希望将条件更改为小于1。但这在https://dotnetfiddle.net/h1AOYF上的dotnetfiddle中起作用了

顺便说一句,您应该将计数器初始化为0,而不是1,这是一个错误。

答案 1 :(得分:1)

有两种方法:

(1)

static void Main(string[] args)
{
    Console.WriteLine("Please enter your first test score");

    double? testScore = TryParse(Console.ReadLine());
    double? sum = 0.0;
    int counter = 0;

    while (testScore.HasValue)
    {
        sum += testScore;
        counter++;

        Console.WriteLine("Please enter your another test score");
        testScore = TryParse(Console.ReadLine());
    }

    if (counter > 0)
    {
        Console.WriteLine("The average of your test score is : {0}", sum / counter);
    }
}

static double? TryParse(string text)
{
    double? result = null;
    if (double.TryParse(text, out double parsed))
    {
        result = parsed;
    }
    return result;
}

(2)

static void Main(string[] args)
{
    Console.WriteLine("Please enter your test scores");

    var scores =
        Enumerable
            .Repeat(0, int.MaxValue)
            .Select(x => TryParse(Console.ReadLine()))
            .TakeWhile(x => x.HasValue)
            .ToArray();

    if (scores.Length > 0)
    {
        Console.WriteLine("The average of your test score is : {0}", scores.Average());
    }
}

static double? TryParse(string text)
{
    double? result = null;
    if (double.TryParse(text, out double parsed))
    {
        result = parsed;
    }
    return result;
}