C 我的贪婪算法有问题吗
当我尝试运行代码时,结果是:C 我的贪婪算法有问题吗,c,cs50,greedy,C,Cs50,Greedy,当我尝试运行代码时,结果是: $ ./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,并尝试对其
$ ./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);
}
#包括
#包括
#包括
内部主(空)
{
流动现金;
做
{
现金=获得浮动(“您的找零是…”);
}
而(现金美分和美分<9);
做{
美分=美分-5;
硬币++;
}
而(5分以上,2分以下);
做{
美分=美分-1;
硬币++;
}
虽然(4>=美分和美分这是错误的:
do{
美分=美分-25美分;
硬币++;
}
分<24分;
这就是所谓的底部测试循环,这意味着只有在对循环体进行至少一次评估之后,才会检查条件。(测试位于循环的底部或末端。)
这对您意味着,即使金额小于25美分,您也会无条件地计算cents=cents-25
。这是不正确的,因为这会使cents
为负值!您需要一个顶级测试的循环,该循环检查是否输入了循环。简单地说,do-while循环需要替换为while循环
但这不是唯一的问题。进入循环的条件是不正确的。只要数量大于或等于25,就应该进入循环。只要数量小于24,就进入循环是完全错误的
最后,您可能需要对每种硬币进行单独计数。您的代码太复杂了。通常使用整数数学是我在链接答案中的答案。谢谢!我不知道关于底部测试循环。