c - 永远运行的贪心程序

标签 c cs50

我最近开发了一个简单的程序,旨在获取一定数量的钱(美元)并确定满足该要求所需的最少硬币数量。

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

int main(void)
{
    // prompts for change and assigns variable owed_change that value
    float owed_change = -1;
    while (owed_change < 0 )
    {
        printf("How much change is owed?\n");
        owed_change = GetFloat();
    }
    // sets the varialble n_coins to 0
    int n_coins = 0;
    // repeats until no more change is owed
    while (owed_change != 0)
    {
        /* checks for the biggest coin that can be used and increases 
        the number of coins by 1 */
        if (owed_change >= .25)
        {
            owed_change -= .25;
            n_coins++;
        }
        else if (owed_change >= .10)
        {
            owed_change -= .10;
            n_coins++;
        }
        else if (owed_change >= .05)
        {
            owed_change -= .05;
            n_coins++;
        }
        else
        {
            owed_change -= .01;
            n_coins++;
        }
    }
    printf("%d\n", n_coins);
}

该程序适用于 .25 的倍数,但适用于任何其他数字。通过测试,我发现它与变量owed_change被减去并得到-0的结果有关,它满足owed_change! = 0。但是,根据研究,我发现作为 float 的 -0 应该作为 +0。如果是这样,我还做错了什么?

最佳答案

在您的情况下,最好将钱作为美分使用并将所有值乘以 100。这样做的原因是 float 不是精确值;这就是为什么您的代码适用于 0.25 等浮点值,但不适用于 0.1、0.05 和 0.01 等较小的 float 的原因。为了您的目的,您最好使用 int 值。

代替:

  • 0.25$,使用 25 美分
  • 0.10$,使用 10 美分
  • 0.05 美元,使用 5 美分
  • 0.01$,使用1美分

在进行上述更改后,将owed_change 的数据类型从float 更改为int。那应该可以解决您的问题。

关于c - 永远运行的贪心程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42798650/

相关文章:

找不到对 GUID_DEVINTERFACE_NET 类的引用

c - 链表 IPC C 语言

密码函数在输出的最后一个字符中产生不需要的结果

c - C 中 ' # ' 字符的右对齐

C数据结构、变量

c - 寻找 `COMPILE_WPRINTF` 的定义

当 valgrind 说没有内存泄漏时,内存泄漏的可能性

python - 如何计算 Python 文本文件中超长字符串中最长的重复字符序列

c - 循环改变不在循环内部的字符串?

使用字符串数组调用整数的 1's, 10' s, 100's... 列