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

我的贪婪算法有问题吗

如何解决我的贪婪算法有问题吗

当我尝试运行代码时,结果是:

 $ ./prueba
    Your change is...0.41
    your cents is 41
    prueba.c:20:19: runtime error: signed integer overflow: -2147483634 - 25 cannot be represented in type 'int'

我不了解整数的错误以及如何解决它,我需要把钱作为浮点数,并计算需要支付的美分,因此我将浮点数乘以x100,然后尝试四舍五入,但不知道为什么不起作用,我的代码是:

#include <cs50.h>
#include <stdio.h>
#include  <math.h>
int main(void)
{   
    float cash;
    do
    {
        cash = get_float("Your change is...");
    }
    while (cash <= -1);
    cash = cash * (100);
    int cents = roundf(cash); 
    int coins = 0;
    printf("your cents is %i\n",cents);
    do{
    cents = cents - 25;
    coins++;
    }   
    while(cents < 24);
    do{
    cents = cents - 10;
     coins++;
    }
    while( 25 > cents && cents < 9);
    do{
    cents = cents - 5;
     coins++;
    }
    while ( 5 > cents &&  cents < 2);
    do{
        cents = cents - 1;
         coins++;
    }
    while ( 4 >= cents && cents <=1);
    printf("Your change is %i coins\n",coins);
}

顺便说一句,这是CS50第1周现金的“轻松”项目,谢谢您的帮助。

解决方法

这是错误的:

do{
    cents = cents - 25;
    coins++;
}   
while(cents < 24);

这就是所谓的“底部测试的循环”,这意味着仅在循环体至少评估了一次之后才检查条件。 (测试在循环的底部或末端。)

这对您意味着什么,即使金额少于25美分,您也无条件评估cents = cents - 25。这是不正确的,因为它会使cents变成负数!您需要一个经过最高测试的循环,该循环检查是否已完全进入循环。简而言之,do-while循环需要替换为while循环。

但这不是唯一的问题。进入循环的条件不正确。只要数量大于或等于25,就应该输入循环。如果数量小于24,则进入循环是完全错误的。

最后,您可能需要为每种硬币单独计数。

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