Greedy Program Running Forever

大兔子大兔子 提交于 2021-02-10 14:36:42

问题


I recently developed a simple program designed to take a certain amount of money (in dollars) and determine the least number of coins necessary to fulfill that requirement.

#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);
}

The program works for multiples of .25 but runs forever for any other number. From testing, I have found out that it has something to do with the variable owed_change being subtracted from and coming to the result of -0, which satisfies owed_change != 0. However, from research, I have found out that -0 as a floating point should act as +0. If so, what else have I done wrong?


回答1:


It would be better, in your case, to work with money as cents and multiply all your values by 100. The reason for this is that floats are not exact values; that would be the reason why your code works for floating point values like 0.25, but not for smaller floating point numbers like 0.1, 0.05, and 0.01. For your purpose, you would be better off using an int value.

Instead of:

  • 0.25$, use 25 cents
  • 0.10$, use 10 cents
  • 0.05$, use 5 cents
  • 0.01$, use 1 cent

Change the data type of owed_change to int from float after making the above changes. That should resolve your problem.



来源:https://stackoverflow.com/questions/42798650/greedy-program-running-forever

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!