【发布时间】:2017-08-17 20:19:15
【问题描述】:
我正在做cs50问题集“贪婪”。基本上是询问用户欠了多少零钱,然后输出可以等于输入金额的最小硬币数量。它工作得很好,除了当我输入 4.2 它输出 22 时它应该输出 18。
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float n;
do
{
n = get_float("How much change is owed?\n");
}
while(n == EOF);
int cents = (int)(n * 100);
int minimumamountofcoins = 0;
if (cents/25 >= 1){
while (cents/25 >= 1)
{
cents -= 25;
minimumamountofcoins++;
}
}
if (cents/10 >= 1){
while (cents/10 >= 1)
{
cents -= 10;
minimumamountofcoins++;
}
}
if(cents/5 >= 1){
while (cents/5 >= 1)
{
cents -= 5;
minimumamountofcoins++;
}
}
if (cents/1 >= 1){
while (cents/1 >= 1)
{
cents -= 1;
minimumamountofcoins++;
}
}
printf("The minimum amount of coins is %d\n", minimumamountofcoins);
}
【问题讨论】:
-
尝试使用调试器逐步完成它。您也可以在 while 循环之前放弃 if 子句,它们基本上测试相同的东西。
-
数千人中又一个“改变”问题。远离浮点,请做一些研究。
-
使用
intinsted 或float进行输入。 -
在
int cents = (int)(n * 100);之后尝试打印美分。此外,所有if条件都是多余的,您可以删除它们。