您好,我在为学校作业创建零钱计算器时遇到问题。它本质上是计算一定数量的货币所需的最低变化量。
- 前任。5.36 美元:
- 2 个玩具(2 美元)
- 1加元(1美元)
- 1 季度
- 1毛钱
- 0 镍币
- 1便士
我已经声明我的所有变量都是双精度数,所以我可以一起计算值和总数。它似乎在整数(5.00、6.00、7.00)上运行良好,但每当我添加小数位时就会出错。就像当我说 5.25 美元时,它应该说 2 toonies 1 loonie 和 1 Quarter。我认为这可能是舍入错误或我的计算有问题。任何帮助表示赞赏。下面是代码的计算:
//Rounding to one number
DecimalFormat oneDigit = new DecimalFormat ("#,0");
//Ask user for input
String moneyinput = JOptionPane.showInputDialog ("Welcome to the Change Caluculator. "
+ "Please Enter your amount of money in Dollars ($): ");
//Take user input and create into string.
totmoney = Double.parseDouble (moneyinput);
//Calculate number of toonies
numtoonies = (totmoney/toonieval);
System.out.println ("There is a total of " + oneDigit.format (numtoonies) + " toonies.");
//Find new amount
totmoney = (totmoney%toonieval);
//Calculate the number of loonies
numloonies = (totmoney/loonieval);
//Find new amount
totmoney = (totmoney-numloonies);
System.out.println ("There is a total of " + oneDigit.format (numloonies) + " loonies.");
//Calculate number of quarters
numquarters = (totmoney/quarterval);
//State the about of Coins
System.out.println ("There is a total of " + oneDigit.format (numquarters) + " quarters.");
}