如何从给定值获取平均值 [英] How to get average from given values
问题描述
我如何平均?我想找到GPA
的平均值,学生总数和GPA
的总数.
例如:
How do I average?. I am suppose to find the average of the GPA
, total of students, and the total of GPA
.
example:
输入: 4 4 4 4
input: 4 4 4 4
输出: 学生总数:4
总GPA :16
平均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);
}
}
推荐答案
如果问题是您得到了错误的答案,则原因是此循环:
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();
}
(其他解决方案也是可能的).在代码的后面,您将需要防止第一个数字为负.如果发生这种情况,count
将为0,并且您要避免除以0并打印无意义的结果.
(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.
这篇关于如何从给定值获取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!