How to get average from given values

前端 未结 3 1386
我寻月下人不归
我寻月下人不归 2021-01-28 15:33

How do I average?. I am suppose to find the average of the GPA, total of students, and the total of GPA. example:

input: 4

3条回答
  •  清歌不尽
    2021-01-28 16:04

    If the problem is that you're getting the wrong answer, the reason is this loop:

    while (GPA >=0)
    {
        GPA = keyboard.nextDouble();
        total = total + GPA;
        count++;
    }
    

    Presumably you intend the loop to exit when the user enters a negative number. What's wrong with it is that it will include the negative number in the total and count. You can rewrite the loop like this:

    GPA = keyboard.nextDouble();
    while (GPA >=0)
    {
        total = total + GPA;
        count++;
        GPA = keyboard.nextDouble();
    }
    

    (Other solutions are possible). Later in your code, you will need to guard against the first number being negative. If that happens, count will be 0 and you want to avoid dividing by 0 and printing nonsense results.

提交回复
热议问题