java - 你如何在java中四舍五入一个双用户输入值?
问题描述
我是一个正在制作简单评分系统的学生,我正在努力解决如何做到这一点
当我输入一个特定的数字时,它会绕过我的 else-if 语句,这些数字是 98、67、98、80 和 81,我不知道为什么会这样
这是我的代码:
public static void main(String[]args) {
double grade=0,tgrade=0,r;
int gcount=0;
for (int i = 0; i<5;i++) {
grade = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the grades "));
tgrade = tgrade+grade;
gcount++;
System.out.println(gcount+". "+"grade: "+grade );
}
DecimalFormat c = new DecimalFormat("##.##");
tgrade = tgrade/500*100;
r = new Double(c.format(tgrade)).doubleValue();
System.out.print("Total Grade: "+(tgrade)+"\n");
if (r >= 95 && r <=100) {
JOptionPane.showMessageDialog(null, "High Honor");
}else if (r >= 90 && r <= 94){
JOptionPane.showMessageDialog(null, "Honor");
}else if (r >=85 && r <= 89) {
JOptionPane.showMessageDialog(null, "Good");
}else if (r>=80 && r<=84) {
JOptionPane.showMessageDialog(null, "Satisfactory");
}else if (r>=75 && r<= 79) {
JOptionPane.showMessageDialog(null, "Low pass, but certifying");
}else {
JOptionPane.showMessageDialog(null, "Low Failure");
}
}
}
解决方案
你的变量 r 是双倍的。
例如 :
You have these numbers : 98, 67, 98, 80 and 81
The average is : 424/5 = 84.8
此值 84.8 不符合您编写的条件:
if (r >=85 && r <= 89)
if (r>=80 && r<=84)
因此它要出去了。
您可以使用以下选项。
第一个选项:不要使用以下范围:
if (r >= 95) {
JOptionPane.showMessageDialog(null, "High Honor");
}else if (r >= 90){
JOptionPane.showMessageDialog(null, "Honor");
}else if (r >= 85){
JOptionPane.showMessageDialog(null, "Good");
}else if (r >= 80){
JOptionPane.showMessageDialog(null, "Satisfactory");
}else if (r >= 75){
JOptionPane.showMessageDialog(null, "Low pass, but certifying");
}else {
JOptionPane.showMessageDialog(null, "Low Failure");
}
第二个选项:如果您使用范围,则将条件框起来,如下所示:
if (r >= 95 && r <= 100) {
JOptionPane.showMessageDialog(null, "High Honor");
}else if (r >= 90 && r < 95){
JOptionPane.showMessageDialog(null, "Honor");
}else if (r >= 85 && r < 90) {
JOptionPane.showMessageDialog(null, "Good");
}else if (r >= 80 && r < 85) {
JOptionPane.showMessageDialog(null, "Satisfactory");
}else if (r >= 75 && r < 80) {
JOptionPane.showMessageDialog(null, "Low pass, but certifying");
}else {
JOptionPane.showMessageDialog(null, "Low Failure");
}
第三个选项:如果您需要四舍五入,那么您可以使用 Math.abs 从double r
例子 :
Math.abs(r)
推荐阅读
- batch-file - 相同的启动命令,不同的结果
- sql - 子查询列太多:查找花费最多的客户最常购买的商品
- c# - C#关于线条图形和屏幕大小的问题
- python - 根据另一列覆盖数据框中的数据
- c - 为什么将编译时静态字符串作为参数传递给字符串格式化函数,而不是将其包含在格式字符串中?
- r - 有没有办法“合并”两列,其中新列的值是具有特定值的原始列的名称,分组明智?
- javascript - 数据表显示条目和搜索功能不起作用
- c# - 具有无法正确关闭 SQL 连接的 ac# 代码(可能)
- css - 当我切换类时,我需要什么代码才能显示正面类?
- r - 使用 mutate 和 case_when 的用户定义函数