微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

CS50现金未返回所需的输出

如何解决CS50现金未返回所需的输出

cs50 greedy algorithm description

这是我的CS50贪婪算法代码。但是,它不会输出任何答案。当我将float dollar更改为int dollars时,它可以工作,但仅适用于大于或等于1的整数。对于0.32这样的数字,它将返回0。如何使我的代码适用于floats?任何帮助表示赞赏。

#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
    float dollars;
    int quarter = 25;
    int dime = 10;
    int nickel = 5;
    int penny = 1;
    do {
          dollars = get_float("Change owed: ");
    } while(dollars <= 0);

    //convert dollars to cents
    int cents = round(dollars * 100);
    int coins = 0;

    while(cents >= quarter) 
    {
         cents -= quarter; //cents = cents - 25;
         coins++;
    }
    while(cents >= dime) {
        cents -= dime;
        coins++;
    }
    while(cents >= nickel) 
    {
        cents -= nickel;
        coins++;
    }
    while(cents >= penny) 
    {
        cents -= penny;
        coins++;
    }
    printf("%i\n",coins);
}

解决方法

#include <stdio.h>

#include <math.h>

#include <cs50.h>

float dollars;
int coins = 0;

int main(void)
{
    //Prompt user for Cash owed and keep doing it until a positive number received
    do
    {
        dollars = get_float("Cash owed: ");
    }
    while (dollars <= 0);

    //Round the cents to the nearest penny
    int cents = round(dollars * 100);

    //Iterate deducting the values from the bigger to the smaller
    while (cents > 0)
    {
        if (cents >= 25)
        {
            cents -= 25;
        }
        else if (cents >= 10)
        {
            cents -= 10;
        }
        else if (cents >= 5)
        {
            cents -= 5;
        }
        else
        {
            cents --;
        }
        coins++;
    }
    //Print the minimal amount of coins
    printf("%i\n",coins);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。