此程序进行更改,除了$ 1.16,为什么这不能正确处理?
public class Change {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Change: ");
double change = in.nextDouble()*100;
int dollars = Math.round((int)change/100);
change=change%100;
int quarters = Math.round((int)change/25);
change=change%25;
int dimes = Math.round((int)change/10);
change=change%10;
int nickels = Math.round((int)change/5);
change=change%5;
int pennies = Math.round((int)change/1);
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
我认为这是一个截断的问题,因为当我在下面的一段代码中使用.9时,它可以工作:
int pennies = Math.round((int)change/.9);
答案 0 :(得分:2)
问题是变化是双重的。当我运行它时,我打印出更改之前的便士声明这是打印的:0.9999999999999858。当它被转换为int时,它变为0.所以0/1为0.不要使用双重模数除法。输入1.16时,返回1.1599999999999999999999999999999。尝试将输入四舍五入。
Scanner in = new Scanner(System.in);
System.out.println("Enter Change: ");
int change = (int)(Math.ceil(in.nextDouble()*100));
int dollars = Math.round((int)change/100);
change=change%100;
int quarters = Math.round((int)change/25);
change=change%25;
int dimes = Math.round((int)change/10);
change=change%10;
int nickels = Math.round((int)change/5);
change=change%5;
int pennies = Math.round((int)change/1);
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
此代码有效。