Создание средней оценки теста с использованием цикла for - PullRequest
0 голосов
/ 28 сентября 2018

Я пытаюсь выяснить, в среднем до 4 баллов по тесту, используя цикл for.Кажется, что я перехожу за 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);
        }


    }

Ответы [ 5 ]

0 голосов
/ 28 сентября 2018

Пожалуйста, попробуйте этот код:

    //variables
    double testScore = 0
    double average = 0;
    double sum = 0;
    for (int count = 1; count <= 4; count++) // Start the count from 0-4
    {
        //get user input
        Console.WriteLine("Please enter test{count} score");
        testScore = double.Parse(Console.ReadLine());

        //now get the sum
        sum = sum + testScore ;
        //Calculate average score
        average = sum / count;
        //Now display the average
        Console.WriteLine("The average of your test score is :", average);
    }

Вот ошибки, которые вы делаете в своем коде:

  1. Запускцикл от count = 0 до count = 4 вызывает неправильное деление.Для 1-й итерации у вас есть одна testScore, но count = 0, это даст ошибку деления на 0.
  2. Вы принимаете входные данные testScore для итерации цикла, но вы не вычисляете среднее значение в той же итерации.Таким образом, он никогда не будет вычислять среднее значение с последним вводом testScore.
0 голосов
/ 28 сентября 2018
Average is not being displayed, because it is never passed to the console.

Измените следующую строку:

Console.WriteLine("The average of your test score is :", 1);

на

Console.WriteLine(string.Format("The average of your test score is : {0}", average/count));

или это (при условии, что Console.Writeline неявно заботится о форматировании строки).

Console.WriteLine("The average of your test score is : {0}", average / count);
0 голосов
/ 28 сентября 2018

Кажется, что ваш for цикл повторяется 5 раз (i = 0,1,2,3,4 (от i = 0 до i = 4))

double average = 0;
double sum = 0;
int numberOfTests = 4;

for (int count = 0; count < numberOfTests; count++) // Start the count from 0-4
{
    Console.WriteLine("Please enter test score " + count); //Console.WriteLine($"Please enter test score {count}");

    double testScore = 0;

    while(!double.TryParse(Console.ReadLine(), out testScore))
    {
        Console.WriteLine("Enter a valid number");
    }

    //get the total
    sum = sum + testScore; //or sum += testScore;
}

//Calculate and display (needs to be outside or else gets printed 4 times)
Console.WriteLine("The average of your test score is : " + sum / numberOfTests);
0 голосов
/ 28 сентября 2018

используйте этот код, это решит вашу проблему, если какой-либо запрос прокомментирует меня.

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

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

            for (int count = 1; count <= 5; 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());
                average = average / count;
                //Calculate and display 
                Console.WriteLine("The average of your test score is {0}", average);
            }


            Console.ReadKey();

            }
0 голосов
/ 28 сентября 2018

Если я вас правильно понимаю, вам нужен знак меньше не меньше или равен

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 (строка s, двойной результат);

Преобразует строковое представлениечисла к его эквиваленту числа с плавающей запятой двойной точности.Возвращаемое значение указывает, успешно ли выполнено преобразование.


Полный пример

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}");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...