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

在java中将int和double相乘时添加括号时出错为什么?,java,int,double,Java,Int,Double,这是一段正常工作的代码,但我想知道,在对Java中的整数和双倍乘法进行了全面研究之后,我仍然不明白为什么代码下面的代码片段会给出错误。需要帮忙吗 public class Arithmetic { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double mealCost = scan.nextDouble(); // original m

这是一段正常工作的代码,但我想知道,在对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;


1.100.123(
double
)*10(
int
)=1001.23(
double

2.1001.23(
double
)/100(
int
)=10.0123(
double

在第二部分:

double tip = mealCost * (tipPercent / 100);
  • 10(
    int
    )/100(
    int
    )=0(
    int

  • 100.123(
    double
    )*0=0(
    double

  • double tip = mealCost * (tipPercent / 100);