在java中乘以int和double时添加括号为什么会出错?

时间:2016-06-24 07:31:32

标签: java int double

这是一个有效的代码,但我想知道在对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);

2 个答案:

答案 0 :(得分:2)

在你的第一个例子中,首先执行乘法,得到一个双数,然后除以100,得到正确的双重结果:

mealCost * tipPercent / 100;

在第2版中,首先执行整数除法,得到整数结果。假设tipPercent小于100,结果将为零。

如果您更喜欢第二个版本,只需使用浮点常量:

double tip = meal * (tipPercent/100.0);

答案 1 :(得分:1)

让我们想象一下:

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);
  1. 10(int)/ 100(int)= 0(int
  2. 100.123(double)* 0 = 0(double