[英]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.