我试图通过使用一系列 while 循环来计算美元和硬币面额的总数。然而,当我拿到硬币时,我差了一分钱。当我输入 99.95 时,我得到 3 个四分之一、1 个硬币、1 个镍和 4 个便士的输出。我已将问题缩小到浮点精度问题。但是,我研究过的所有解决方案都不适用于我的情况。任何指针?
#include <iostream>
using namespace std;
int main()
{
float amount;
cout<<"enter amount" << endl;
cin>>amount;
int pennies=0, nickels=0, dimes=0, quarters=0, ones=0, fives=0,
tens=0,
twenties=0, fifties=0, hundreds=0;
while (amount >= 100)
{
hundreds = hundreds +1;
amount = amount - 100;
}
while (amount >= 50)
{
fifties = fifties +1;
amount = amount - 50;
}
while (amount >= 20)
{
twenties = twenties +1;
amount = amount - 20;
}
while (amount >= 10)
{
tens = tens +1;
amount = amount - 10;
}
while (amount >= 5)
{
fives = fives +1;
amount = amount - 5;
}
while (amount >= 1)
{
ones = ones +1;
amount = amount - 1;
}
while (amount >= .25)
{
quarters = quarters +1;
amount = amount - .25;
}
while (amount >= .10)
{
dimes = dimes +1;
amount = amount - .10;
}
while (amount >= .05)
{
nickels = nickels +1;
amount = amount - .05;
}
while (amount >= .01)
{
pennies = pennies +1;
amount = amount - .01;
}
cout<<endl<<"pennies:"<< pennies;
cout<<endl<<"nickels:"<<nickels;
cout<<endl<<"dimes:"<<dimes;
cout<<endl<<"quarters:"<<quarters;
cout<<endl<<"ones:"<<ones;
cout<<endl<<"fives:"<<fives;
cout<<endl<<"tens:"<<tens;
cout<<endl<<"twenties:"<<twenties;
cout<<endl<<"fifties:"<<fifties;
cout<<endl<<"hundreds:"<<hundreds<<endl;
return 0;
}