所以我被分配为我的编程类编写一个程序,提示用户并将输入的值读取为double(最大输入为[99.99]九十九美元,九十九美分),这将代表一个货币金额。然后,我要确定代表所述金额所需的每张账单和硬币的最少数量(10美元的钞票是所需的最大尺寸)。
我遇到了四舍五入的问题。例如,输入99.99将返回3便士,当它应该是4便士。我的老师明确告诉我,不要超越课堂上的材料(只有创建扫描仪,转换数据类型和转换。这意味着没有BigDecimal)。任何帮助将不胜感激。
import java.util.Scanner;
public class MoneyConversion
{
public static void main(String[] args)
{
//Set variables for input, dollars, and cents
double inputAmount, change;
int tens, fives, ones;
int quarters, dimes, nickels, pennies;
//Create scanner to setup for user input
Scanner scan = new Scanner(System.in);
//Scan user input and store into double
System.out.print("Enter monetary amount: ");
inputAmount = scan.nextDouble();
//Extract demical or cent amount from dollar amount
change = (inputAmount - (int) inputAmount) * 100;
System.out.println("That's equivalent to:");
//Extract and print denomination for ten-dollar bills
tens = (int) inputAmount / 10;
inputAmount = inputAmount % 10;
System.out.println(tens + " ten dollar bills");
//Extract and print denomination for five-dollar bills
fives = (int) inputAmount / 5;
inputAmount = inputAmount % 5;
System.out.println(fives + " five dollar bills");
//Extract and print denomination for one-dollar bills
ones = (int) inputAmount;
System.out.println(ones + " one dollar bills");
//Extract and print denomination for quarters
quarters = (int) change / 25;
change = change % 25;
System.out.println(quarters + " quarters");
//Extract and print denomination for dimes
dimes = (int) change / 10;
change = change % 10;
System.out.println(dimes + " dimes");
//Extract and print denomination for nickels
nickels = (int) change / 5;
change = change % 5;
System.out.println(nickels + " nickels");
//Convert value for change to integer value and print for pennies
pennies = (int) change;
System.out.println(pennies + " pennies");
}
}
答案 0 :(得分:0)
你最好将数字转换为整数(便士的数量)并根据它进行计算,因为这样你可以避免你现在遇到的浮点错误的类型(它们是由将浮点数表示为二进制)。
如果您逐步使用this(您需要对输入进行硬编码才能使用它),您可以看到错误。
由于第20行的舍入,更改金额设置为98.99999999999949
,这就是为什么缺少一分钱