最近我正在学习计算机科学课程的一部分,学习了一点C语言。其中一个挑战是创建一个程序来告诉收银员需要多少硬币才能为客户找零。我用一组while循环完成了这个任务,整个程序看起来像这样:
#include <stdio.h>
#include <cs50.h>
int main(void)
{
float f;
int i;
i=0;
do
{
f = get_float("Input Change: \n");
}
while(f<0);
// This do-while loop uses a get_float operator to get a postive input from the user.
while(f>=0.25)
{
f=f-0.25;
i=i+1;
}
// Each one of these loops represents using one kind of coin. For this one, every time it runs it adds
// one coin to the final tally and removes 25 cents from the change owed.
while(f>=0.10)
{
f=f-0.10;
i=i+1;
}
// Dime loop, subtracts ten from change owed.
while(f>=0.05)
{
f=f-0.0500000;
i=i+1;
}
// Nickel loop, subtracts five from change owed.
while(f>0)
{
f=f-0.01;
i=i+1;
}
// Penny loop, subtracts one from change owed.
printf("You need %i coins.%f\n", i, f);
//This just prints the number of coins needed.
}
问题在于,即使没有理由执行最后一个while循环,我们仍然会随机执行它。例如,$0.42返回正确的值,而$0.15会导致最后一个while循环无缘无故地增加一分钱。
while(f>0)
{
f=f-0.01;
i=i+1;
}
(问题中有问题的 while 循环)
我对编程非常新手,所以这可能只是因为我做了一些傻事而导致的问题,但我不知道具体哪里出错了。有人之前遇到过这个问题吗?
f
的值,我怀疑您可能存在浮点舍入误差。也许使用整数来表示整个美分会使数学计算更容易。 - Drew Reesecs50.h
不具备可移植性。 - user3629249float
类型表示货币值是非常危险的,因为float
类型并不能保证百分之百正确的值。 - user3629249for
、if
、else
、while
、do...while
、switch
、case
、default
代码块分隔开来。