为什么最后一个计算会打印出错误的计算。这是我的代码:
System.out.print(“输入总成本:”);
double totalCost = input.nextDouble();
System.out.print("The Customer has paid: ");
double customerAmount = input.nextDouble();
//Calculations
double changeOwed = customerAmount - totalCost;
System.out.println("Change owed: $"+(int)changeOwed);
int amountFifty = (int)changeOwed/50;
System.out.println("How many $50 notes = " +amountFifty);
int takeAway = (int)changeOwed - (amountFifty * 50);
int amount20 = takeAway / 20;
System.out.println("How many $20 notes = " +amount20);
int amount10 = (takeAway - amount20*20) / 10;
System.out.println("How many $10 notes = " +amount10);
enter code here
int amount5 = (takeAway - amount10*10) / 5;
System.out.println("How many $5 notes = " +amount5);
int amount2 = (takeAway - amount5*5) / 2;
System.out.println("How many $2 notes = " +amount2);
int amount1 = (takeAway - amount2*2) /1;
System.out.printl
n(“多少个$ 1钞票=” + amount1);
您没有正确跟踪沿途发布的更改。
int takeAway = (int)changeOwed - (amountFifty * 50);
上面的行正确地确定了所需的50美元面额的钞票后剩余的东西。这意味着:
int amount20 = takeAway / 20;
int amount10 = (takeAway - amount20*20) / 10;
正确计算10美元和20美元的钞票数。
int amount5 = (takeAway - amount10*10) / 5;
是不正确的,因为您没有减去20美元面额的钞票。您在计算$ 2时也犯了类似的错误,即。您不需支付$ 20和$ 10的费用。 $ 1的错误复合。