首页 > 解决方案 > java中的if语句+计算总数

问题描述

当我用java编写这个例子时,我遇到了一个问题:

if ( deadline==1){ 
    total = A + B + C;
    System.out.println(" you get =" + total);
}
if ( deadline==2 ){ 
    total = A + B + C;
    Punishment = total*(5\100);
    Final = total - Punishment;
    System.out.println(" you get =" + Final);
}

当我运行它时,我在黑屏上写了最后期限=2
,但它显示在黑屏上(你得到=总计)

要清楚我有(A,B,C)的值。我在if声明之前写 + 我之前要求用户使用Scanner.

标签: javaif-statement

解决方案


在 Java 中,如果一个运算的两个操作数都是整数,则该运算作为整数运算完成。

您的代码正在执行Punishment = total*(5\100)- 这里除法是作为整数运算完成的,也就是说,结果(5*100)0(零),因此Punishment也将是零。

选项1:将其更改Punishment = (total * 5) \ 100为首先完成乘法(不需要括号)。

选项2:使用双重喜欢Punishment = (int)(total * (5.0\100))

选项 3:也将变量更改为双精度:

double punishment;
...
punishment = total * 5.0 / 100.0;

注意:变量名按约定应以小写字母开头

假设deadline2


推荐阅读