[英]Error when adding parenthesis in multiplying int and double in java why?
这是一个有效的代码,但是我想在对Java中的整数和双精度进行全面研究之后仍不知道为什么代码下方的代码片段会产生错误。 有什么帮助吗?
public class Arithmetic {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double mealCost = scan.nextDouble(); // original meal price
int tipPercent = scan.nextInt(); // tip percentage
int taxPercent = scan.nextInt(); // tax percentage
scan.close();
// Calculate Tax and Tip:
double tip = mealCost * tipPercent / 100; //HERE IS MY PROBLEM
double tax = mealCost * taxPercent / 100; //HERE IS MY PROBLEM
// cast the result of the rounding operation to an int and save it as totalCost
int totalCost = (int) Math.round(mealCost + tax + tip);
System.out.println("The total meal cost is " + totalCost + " dollars.");
}
}
知道这个答案比上面的答案更合乎逻辑并且给出了不同的值吗?
double tip = meal * (tipPercent/100);
double tax = meal * (taxPercent/100);
在第一个示例中,首先执行乘法运算,得到一个双精度数,然后将其除以100,得出正确的双精度结果:
mealCost * tipPercent / 100;
在第二版中,首先执行整数除法,从而得出整数结果。 假设tipPercent
小于100,结果将为零。
如果您更喜欢第二个版本,请使用浮点常量:
double tip = meal * (tipPercent/100.0);
想象一下:
int tipPercent = 10;
double mealCost = 100.123d;
和
double tip = mealCost * tipPercent / 100;
1. 100.123( double
)* 10( int
)= 1001.23( double
)
2. 1001.23( double
)/ 100( int
)= 10.0123( double
)
在第二:
double tip = mealCost * (tipPercent / 100);
int
)/ 100( int
)= 0( int
) double
)* 0 = 0( double
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.