贪婪算法:“未使用表达式结果”

时间:2019-08-01 06:08:09

标签: c cs50

我正在尝试为CS50做一个贪心算法,但是由于某些原因,在尝试将总分除以25、10、5等时,我总是收到错误消息,表示“表达式结果未使用”。有人可以指出我要去哪里错了?提前非常感谢您。

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
float Change;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
int count = 0;

do
{
    Change = get_float("Change: ");
}
while (Change < 0);

int cents = round(Change * 100);

while (cents % 25 >= 25)
 { 
    cents/25;
    count = count + 1;
 }


 while (cents % 10 >= 10)
 {
     cents/10;
     count = count + 1;
 }


while (cents % 5 >= 5)
{
    cents/5;
    count = count + 1;
}


while (cents % 1 >= 1)
{
    cents/1;
    count = count + 1;
}


printf("%d coins", count);

}

2 个答案:

答案 0 :(得分:0)

比较错误

以下情况永远都不成立。除后的余数cents % 25始终小于25。

while (cents % 25 >= 25)

无用的代码

以下内容除以25,然后丢弃商。 @Some programmer dude

cents/25;

取而代之的是25、10、5、1个地方

// while (cents % 25 >= 25)
while (cents >= 25)

// cents/25;
cents -= 25;

可能会有更有效的代码。提示:不需要while循环。


很好地将输入转换为整数。

更深:

int cents = round(Change * 100);float产生Change * 100乘积,然后在调用double时转换为round(double)。最后,作为分配的一部分,它将结果转换为int

可以使用roundf(float)并跳过double转换。

对于学习者代码,这是一个好的开始。请注意,Change * 100可能会导致舍入误差,在某些情况下,如果舍入误差接近0.5美分,该误差会显示出来。建议round(Change * 100.0)

也许使用long lround(double x)来完成从double到整数的最终转换。

请注意,输入太大会导致溢出和不确定的行为

答案 1 :(得分:-1)

就像错误消息告诉您的那样:您正在计算的cents/n值不会随处可见。我认为您正在尝试做cents = cents/n。 另外,您的while循环正在检查cents的值,但是您正在递增变量count。因此,您将永远不会退出循环。

相关问题