samedi 8 mai 2021

C# it shows null in Console for an else condition, instead of what I want it to display

So I have this code that will calculate the arithmetic mean. The user has to introduce random numbers, and when the input is "x" the code will stop and calculate the arithmetic mean. The code works fine if I introduce any numbers. However, if the first input is "x" I have to display "0". In the console, I get null ("") instead of 0.

The problem is the 'else' condition, the rest of the code works as expected. I tried to write the condition in different ways and even to put it in another block because I thought it is unreachable, but it is still null. I am not sure what I am missing.

Thank you in advance!

Blockquote

        string line = Console.ReadLine();
        double sum = 0;
        double count = 0;

        while (line != "x")
        {
            double number = Convert.ToInt32(line);
            sum += number;
            count++;
            line = Console.ReadLine();

            if (line == "x")
            {
                if (count > 0)
                {
                    double ma = sum / count;
                    Console.WriteLine((float)ma);
                }

                else {
                    Console.WriteLine(0);
                }
            }
        }

Aucun commentaire:

Enregistrer un commentaire