How to get average from given values

允我心安 提交于 2019-12-31 05:12:17

问题


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 4 4 4

output: Total Students:4

Total GPA:16

Average GPA: 4

import java.util.Scanner;

public class practice {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int count = 0;
        double GPA = 0, total = 0, average;

        System.out.println("Enter GPA");

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

        average = total / count;

        System.out.println("Total students: " + count);
        System.out.println("Total GPA " + total);
        System.out.println("Average GPA " + average);
    }
}

回答1:


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.




回答2:


You are getting the input in your loop at this line

GPA = keyboard.nextDouble();

Problem is that, it will get another input and count will be incremented by 1. So your total will be 5. You can probably make it in this way

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



回答3:


Just swap the order of your statements in the while loop and your code should work fine. In this case,your check (whether to add the i/p to the total) will be done after you key in. Hence,when you key in -1,the you won't enter the while loop and the last value of -1 won't be added.

while (GPA >=0) {

total = total + GPA;
GPA = keyboard.nextDouble();
count++;

}



来源:https://stackoverflow.com/questions/15516797/how-to-get-average-from-given-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!