0

I am having trouble figuring out why my code keeps on looping back rather than giving me my average after entering 0. Please advise:

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

    }
}

}

Quang P.
  • 77
  • 8

2 Answers2

2

You might wanna change the condition to be less than 1. But it is working on dotnetfiddle here https://dotnetfiddle.net/h1AOYF

btw, you should initialize your counter with 0, not 1, that's a bug.

AD.Net
  • 13,062
  • 2
  • 26
  • 44
1

Here are two approaches:

(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;
}
Enigmativity
  • 97,521
  • 11
  • 78
  • 153