动态计算更改为最接近的10美元

时间:2013-10-16 16:11:11

标签: java

我是Java的新手,我正在试图弄清楚如何动态计算更改到最接近的10美元。例如,用户输入一个值(34.36),然后我的代码计算账单的提示,税金和总金额(总计44.24)。没有用户输入,我需要计算50.00美元的变化。我试图在没有运气的情况下从44.24累计到50.00,显然我做错了。我尝试过Math.round并尝试使用%找到余数。任何有关如何通过最接近的10美元价值获得总变化的帮助都会很棒。提前谢谢,下面是我的代码: 全力以赴,这是一个家庭作业项目。

import java.util.Scanner; 
import java.text.NumberFormat;
import java.lang.Math.*;

public class test1
{
public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    //Get input from user
    System.out.println("Enter Bill Value:                   ");
    double x = sc.nextDouble();

    //Calculate the total bill
    double salesTax = .0875;
    double tipPercent = .2;
    double taxTotal = (x * salesTax);
    double tipTotal = (x * tipPercent);
    double totalWithTax = (x + taxTotal);
    double totalWithTaxAndTip = (x + taxTotal + tipTotal);

    //TODO:  Test Case 34.36...returns amount due to lower 10 number
    //This is where I am getting stuck                  
    double totalChange = (totalWithTaxAndTip % 10);




    //Format and display the results
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    NumberFormat percent = NumberFormat.getPercentInstance();

    //Build Message / screen output
    String message =
        "Bill Value:                         " + currency.format(x) + "\n" + 
        "Tax Total:                          " + currency.format(taxTotal) + "\n" +
        "Total with Tax:                     " + currency.format(totalWithTax) + "\n" +
        "20 Percent Tip:                     " + currency.format(tipTotal) + "\n" +
        "Total with Tax and 20 Percent Tip:  " + currency.format(totalWithTaxAndTip) + "\n" +
        "Total Change:                       " + currency.format(totalChange) + "\n";

    System.out.println(message);

}
}

4 个答案:

答案 0 :(得分:1)

你做了            double totalChange = round((totalWithTaxAndTip / 10)) * 10;

答案 1 :(得分:0)

Math.ceil(double)将向上舍入一个数字。所以你需要的是这样的东西:

 double totalChange = (int) Math.ceil(totalWithTaxAndTip / 10) * 10;

对于totalWithTaxAndTip = 44.24,totalChange = 50.00

对于totalWithTaxAndTip = 40.00,totalChange = 40.00

答案 2 :(得分:0)

Math.round将数字四舍五入到最接近的整数,正如其他人所示,你需要除以10,然后在四舍五入后乘以10:

double totalChange = tenderedAmount - totalWithTaxAndTip;

double totalChangeRounded  = 10 * Math.round(totalChange / 10);

答案 3 :(得分:0)

每个人,非常感谢你帮助我。我测试了每个人的解决方案。这是我最后的工作代码......

double totalAmountPaid = totalWithTaxAndTip - (totalWithTaxAndTip % 10) + 10;   

我使用许多不同的值测试了它,它似乎按照我想要的方式工作。

同样,我感谢大家花时间帮助我。