我是 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);
}
}