Math.round不会舍入数字

时间:2017-08-03 00:21:34

标签: java math rounding

晚安,

我的代码不会圆满,我不知道为什么!请帮忙!

import java.util.*;
import java.math.*;

public class Arithmetic {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int tipPercentage;  // tip percentage
        int taxPercentage;  // tax percentage
        int totalTip;       // total tip
        int totalTax;       // total tax
        double mealCost;    // original meal price
        double totalCost = 0.0; // total meal price

        // Write your calculation code here.
            mealCost = scan.nextDouble();
            tipPercentage = scan.nextInt ();
            taxPercentage = scan.nextInt();

            totalCost += mealCost;
            totalCost += mealCost*tipPercentage/100;
            totalCost += mealCost*taxPercentage/100;


        // cast the result of the rounding operation to an int and save it as totalCost 
            mealCost=(int)Math.round(totalCost);


        // Print your result
        System.out.println (" The total meal cost is " + totalCost + " dollars. ");
    }
}

2 个答案:

答案 0 :(得分:0)

当您为totalCost指定舍入值时,您将mealCost附加到打印的字符串。换句话说,

mealCost=(int)Math.round(totalCost);

应该成为

totalCost=(int)Math.round(totalCost);

此外,您可能希望在接受输入之前添加提示以及重新考虑您的舍入,除非您真的希望它到最接近的美元。

答案 1 :(得分:-1)

mealCost是您尝试舍入的变量,而totalCost是您打印并显示给用户的变量。

System.out.println (" The total meal cost is " + totalCost + " dollars. ");

此外,在显示成本时,最好将其舍入到最接近的百分之一。你可以通过说

之类的东西来做到这一点

mealCost=Math.round(totalCost*100)/100.0

最后,您应该提示用户,以便他们知道他们在控制台中输入的内容。