我的主类中有这段代码。我的问题是,GPA 是用总分除以班级来计算的。它没有给我完整的号码。 EX,如果总数为 14,班级为 4,则为 3.5,我的代码只给我 3.0。有谁知道为什么,我非常感谢您的帮助!
Scanner input = new Scanner(System.in);
System.out.print("How many classes did you have?: ");
int classes = input.nextInt();
String grades = "";
int total = 0;
int dec;
for (int j = 0; j < classes; j++) {
Scanner inputters = new Scanner(System.in);
System.out.print("What is your Grade?: ");
grades = inputters.nextLine();
if (grades.equals("A")){
dec = 4;
total += dec;
} else if (grades.equals("B")){
dec = 3;
total += dec;
} else if (grades.equals("C")){
dec = 2;
total += dec;
} else if (grades.equals("D")){
dec = 1;
total += dec;
} else if (grades.equals("F")){
dec = 0;
total += dec;
}
}
double GPA = total / classes;
System.out.println(GPA);
DecimalFormat formatter = new DecimalFormat("0.##");
System.out.println( formatter.format(GPA));
这是因为你将 int 除以 int,这永远不会得到浮点数。将总计/课程类型更改为双倍(或转换),GPA 将是您期望的数字。
PS:并不是说双精度数不太准确,例如 0.9 + 0.1 != 1.0。如果您想进行“正确的”双精度计算,请使用 BigDecimal,并在使用 String 构造函数时使用它们。
使用 double 而不是 int 来转换变量。