简体   繁体   English

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

[英]Error when adding parenthesis in multiplying int and double in java why?

This is a working code but I am wondering after a full research on multiplying ints and doubles in Java I still can't see why the snippet below the code would give an error. 这是一个有效的代码,但是我想在对Java中的整数和双精度进行全面研究之后仍不知道为什么代码下方的代码片段会产生错误。 Any help please? 有什么帮助吗?

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.");
    }
}

Knowing that this answer is more logical and gives a different value than the one above?! 知道这个答案比上面的答案更合乎逻辑并且给出了不同的值吗?

double tip = meal * (tipPercent/100);
double tax = meal * (taxPercent/100);

In your 1st example, the multiplication is performed first, resulting in a double number that is then divided by 100, giving the correct double result: 在第一个示例中,首先执行乘法运算,得到一个双精度数,然后将其除以100,得出正确的双精度结果:

mealCost * tipPercent / 100;

In your 2nd version, an integer division is performed first, resulting in an integer result. 在第二版中,首先执行整数除法,从而得出整数结果。 Assuming that tipPercent less than 100, the result will be zero. 假设tipPercent小于100,结果将为零。

If you like the second version better, just use a floating point constant: 如果您更喜欢第二个版本,请使用浮点常量:

double tip = meal * (tipPercent/100.0);

Let's imagine: 想象一下:

int tipPercent = 10;
double mealCost = 100.123d;

And

double tip = mealCost * tipPercent / 100;


1. 100.123( double ) * 10( int ) = 1001.23( double ) 1. 100.123( double )* 10( int )= 1001.23( double
2. 1001.23( double ) / 100( int ) = 10.0123( double ) 2. 1001.23( double )/ 100( int )= 10.0123( double

In the second: 在第二:

double tip = mealCost * (tipPercent / 100);
  1. 10( int ) / 100( int ) = 0( int ) 10( int )/ 100( int )= 0( int
  2. 100.123( double ) * 0 = 0( double ) 100.123( double )* 0 = 0( double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM