因为某种原因,我的程序是计算GPA平均数错误。如果我三次输入4.0,它说平均GPA是3.0,但应该是4.0。有人能帮我找到这个问题吗?
//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;
do
{
String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
if (gpa >= 3.5)
counter2 ++;
total += gpa;
counter ++;
}
while (gpa != 0);
double average = (double) (total/counter);
JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);发布于 2015-11-13 02:36:37
让我们走一遍代码
但是为时已晚,我们已经增加了counter,所以我们的average计算是错误的
发布于 2015-11-13 02:29:49
问题是,如果用户输入0,则运行程序,然后退出。
尝试这段代码(对不起,我目前没有编辑器,所以您可能需要修复一些小问题)。
//variables
double gpa = 0;
double total = 0;
int counter = 0;
int counter2 = 0;
String gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
while (gpa != 0) {
if (gpa >= 3.5)
counter2 ++;
total += gpa;
counter ++;
gpaEntry = JOptionPane.showInputDialog("Please enter GPAs:");
gpa = Double.parseDouble(gpaEntry);
}
JOptionPane.showMessageDialog(null, "The Average GPA is: " + average);
JOptionPane.showMessageDialog(null, "Number of students:" + counter2);如果你还有其他问题,请发表评论。
https://stackoverflow.com/questions/33684884
复制相似问题