我的编程课程的练习要求我们为收银员编写一个程序,提示应付金额和收到的金额并计算更改。它还必须计算所需的美元,四分之一,硬币,硬币和便士的数量。它工作正常,直到达到硬币,镍币和硬币。这就是输出变得不稳定的地方。我还注意到visual studio读取0.10为.1000000000000000056。镍和硬币也是如此,但美元或季度不会发生这种情况。我已经尝试了几种不同的方法来解决它,但没有运气。任何建议
cout << "Amount Due. \n";
double due;
cout << "$";
cin >> due;
cout << "Amount recieved. \n";
double rec;
cout << "$";
cin >> rec;
double change = (rec - due);
cout << "Total change= $" << change << " \n";
int dollars = change / 1.00;
change = change - dollars;
int quarters = change / .25;
change = change - quarters;
int dimes = change / .10;
change = change - dimes;
int nickels = change / .05;
change = change - nickels;
int pennies = change / .01;
change = change - pennies;
cout << "Number of dollars: " << dollars << " \n";
cout << "Number of quarters: " << quarters << " \n";
cout << "Number of dimes: " << dimes << " \n";
cout << "Number of nickels: " << nickels << " \n";
cout << "Number of pennies: " << pennies << " \n";
return 0;
}
答案 0 :(得分:0)
while(change > 0){
if(change >= 1.00){
dollars ++;
change -= 1;
continue;
}
if(change >= 0.25){
quarters ++;
change -= 0.25;
continue;
}
if(change >= 0.10){
dimes ++;
change -= 0.1;
continue;
}
if(change >= 0.05){
nickels ++;
change -= 0.05;
continue;
}
if(change >= 0.01){
pennies ++;
change -= 0.01;
continue;
}
}
continue
关键字从顶部再次启动循环。
此实现可抵抗浮点不准确性。