我是Java新手,我正在尝试弄清楚如何动态地计算到最接近10美元的零头。例如,用户输入一个值(34.36),然后我的代码就会计算账单的小费、税金和总金额(总计44.24)。如果没有用户输入,我需要从$50.00开始计算变化。我试图从44.24四舍五入到50.00,但没有运气,显然我做错了什么。我已经尝试了Math.round,并尝试使用%查找剩余部分。任何关于如何获得由于最近的10美元价值的总变化的帮助将是很大的。提前谢谢你,下面是我的代码: Full dis-closer,这是一个作业项目。
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);
}
}发布于 2013-10-17 00:17:24
你让double totalChange = round((totalWithTaxAndTip / 10)) * 10;
发布于 2013-10-17 00:19:00
Math.ceil(double)将向上舍入一个数字。所以你需要的是这样的东西:
double totalChange = (int) Math.ceil(totalWithTaxAndTip / 10) * 10;对于totalWithTaxAndTip =44.24时,totalChange = 50.00
对于totalWithTaxAndTip = 40.00,totalChange = 40.00
发布于 2013-10-17 00:21:37
Math.round将一个数字舍入为最接近的整数,因此,正如其他人所示,您需要除以10,然后在舍入后乘以10:
double totalChange = tenderedAmount - totalWithTaxAndTip;
double totalChangeRounded = 10 * Math.round(totalChange / 10);https://stackoverflow.com/questions/19408425
复制相似问题