2017-08-03 97 views
0

晚上好,Math.round不会四舍五入

我的代码不会四舍五入,我不知道为什么!请帮忙!

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

你的问题有点含糊不清,你能不能请编辑一下更详细的问题 –

+1

你有一个错字,但整个方法是错误的。在重复的原因中查看我的答案。如果你想要小数位,你必须使用小数基数,例如通过'BigDecimal'或'DecimalFormat',在任何情况下你都应该使用'BigDecimal'来赚钱,而不是浮点。 – EJP

回答

-1

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

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

此外,显示成本时,它可能是一个好主意,四舍五入到最接近的百分之一。你可以说像

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

做到这一点。最后,你应该提示用户,让他们知道他们在控制台正在输入。

+0

非常感谢!这很有意义。 –

+0

当然,在上面的例子中,您可能想要将mealCost更改为totalCost ...我只是不确定要打印哪一个。 –

+0

你应该使用BigDecimal来获得金钱,而不是浮点。 –

0

要附加totalCost到您的打印字符串,当你到mealCost分配舍入的值。换句话说,

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

应该成为

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

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

+0

所以这实际上工作,因为它显示我的总数从15.36变为15.0 ...有没有办法从最终结果中删除.0部分? –

+0

如果您想摆脱.0,那么只需在您的打印语句中将mealCost作为int来投射。 –