我已经在PSET1的CS50中完成了贪婪挑战的代码
但是,硬币返还的总数非常大。当我进一步研究时,似乎我的镍币数量巨大(4381344个硬币,占0.48美分)。
叫我愚蠢,但因为这个原因我已经拔了一段时间。谁能指出原因?
#include <cs50.h>
#include <stdio.h>
#include <math.h>
// You want to:
// get user input of a float
// check float
// Loop: minus money with biggest coins unit until negative
// then loop and loop
// until 1
// then count the number of loop (by assign a variable to count)
int main(void)
{
float money_give;
int quarters= 25, qc, dimes = 10, dc, nickels= 5, nc,pennies= 1, pc;
do
{
printf("O hai! How much change is owed?\n");
money_give = get_float();
}
while (money_give <= 0.0);
money_give = money_give * 100;
int money = (int)round(money_give);
while (money >= quarters)
{
qc = money / quarters;
money = money % quarters;
}
while (money >= dimes)
{
dc = money / dimes;
money = money % dimes;
}
while (money >= nickels)
{
nc = money / nickels;
money = money % nickels;
}
while (money >= pennies)
{
pc = money / pennies;
money = money % pennies;
}
printf("%i\n",pc+ nc+ qc +dc);
printf("%i\n",nc);
printf("%i\n",qc);
printf("%i\n",dc);
printf("%i\n",pc);
}
哦,输出是:
O hai! How much change is owed?
0.48
4381350
4381344
1
2
3
最佳答案
您忘记了初始化变量。更改:
int quarters= 25, qc, dimes = 10, dc, nickels= 5, nc,pennies= 1, pc;
变成:
int quarters= 25, qc = 0, dimes = 10, dc = 0, nickels= 5, nc = 0, pennies= 1, pc = 0;
发生的事情是,因为
nc
尚未初始化,所以它开始时等于存储它的内存中已经存在的任何垃圾。然后,当您进入这一部分时,它没有获得新值,因为
money
小于nickels
: while (money >= nickels)
{
nc = money / nickels;
money = money % nickels;
}
因此,它永远不会被分配一个新值,而不是开始时分配的垃圾。
从中得到的教训是:始终初始化变量。
关于c - CS50 pset1-贪婪挑战的奇怪总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44131418/