为什么最后一次美元汇率计算错误

问题描述 投票:0回答:1

为什么最后一个计算会打印出错误的计算。这是我的代码:

System.out.print("Enter total cost: ");

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("How many $1 notes = " +amount1);
java calculator division difference modulus
1个回答
1
投票

您没有正确跟踪沿途发布的更改。

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美元面额的钞票,只减去10美元面额的钞票。您在计算$ 2时也犯了类似的错误,即。您不需支付$ 20和$ 10的费用。 $ 1的错误复合。

您可以尝试以下方法:

    int amountFifty = changeOwed / 50;
    double takeAway = changeOwed - (amountFifty * 50);
    int amount20 = takeAway / 20;
    takeAway -= (amount20 * 20);
    int amount10 = takeAway / 10;
    takeAway -= (amount10 * 10);
    int amount5 = takeAway / 5;
    takeAway -= (amount5 * 5);
    int amount2 = takeAway / 2;
    takeAway -= (amount2 * 2);
    int amount1 = takeAway / 1;
© www.soinside.com 2019 - 2024. All rights reserved.