我正在尝试解决CS50的贪婪问题,但它无法正确计算。我总是留下0.01而不是0.00的剩余价值。一切都顺利,除了最后的便士。我不知道该怎么做。当您输入更改时,请尝试9.99。没有便士的数字它工作正常。
非常感谢!
int main()
{
// declaring variables for coins
float const qtr = 0.25;
float const dimes = 0.10;
float const nick = 0.05;
float const penny = 0.01;
//declaring variables for coin counters
int qtr_count = 0;
int dimes_count = 0;
int nick_count = 0;
int penny_count = 0;
//declaring variables for total debt and rest of debt
float total;
float rest;
//loop for testing is the number entered valid
do
{
printf("Enter the ammount of money he owns:\n");
scanf("%f", &total);
}
while (total < 0.00) ;
rest = total;
//Loop for calculating coins
while (rest >= qtr)
{
qtr_count++;
rest -= 0.25;
}
while (rest >= dimes)
{
dimes_count++;
rest -= 0.10;
}
while (rest >= nick)
{
nick_count++;
rest -= 0.05;
}
while (rest >= penny)
{
penny_count++;
rest -= 0.01;
}
printf("You need go give: \n %i quarters, \n %i dimes, \n %i nick, \n %i pennies \n", qtr_count, dimes_count, nick_count, penny_count);
return 0;
}
答案 0 :(得分:0)
问题可能是浮点运算并不总是精确的。我建议你只使用整数。让人输入以美分为单位的金额(或乘以100)。这样你就不会遇到任何浮点运算问题,也会更有效率。