Joh*_*son 0 c greedy while-loop cs50
我试图用输入编写贪婪算法,该算法应返回更改中要使用的最小硬币数,但不返回任何值。我不知道为什么。它只是要求输入,然后什么也不显示。
我创建了一个先前的线程,其中确定了一个导致无限循环的错误,该错误被压缩,但是现在我的逻辑中似乎还有另一个潜在的错误。
#include <stdio.h>
#include <cs50.h>
#include <math.h>
// declare variable change_owed, num_coins, and input globally
float change_owed = 0;
float input;
int num_coins;
int main(void)
{
// makes sure the input is non-negative
do
{
input = get_float("Amount paid\n");
}
while(input <=0);
// begin checking
while(input > 0)
{
if(input - .25 >= 0) // quarters
{
num_coins++; // number of coins used, to be printed later, is incremented
input = input - .25; // coin is subtracted from total
}
if (input - .10 >= 0) // dimes
{
num_coins++;
input = input - .10;
}
if (input - .05 >= 0) // nickels
{
num_coins++;
input = input - .05;
}
if (input - .01 >= 0) // pennies
{
num_coins++;
input = input - .01;
}
}
printf("%i", num_coins);
}
Run Code Online (Sandbox Code Playgroud)
在的常用格式中double
,.10
不是.10,而是0.100000001490116119384765625。此外,您使用的float
变量(float input
)与double
常量(.10
,.05
,.01
)。在某个时候,您的程序还有零钱之类的剩余金额,例如.00999…5,因此它没有要减去的硬币,因此代码永远循环而不减任何东西。为了解决这个问题,只要获得input
,将其乘以100,将其四舍五入为最接近的整数(与一样int cents = roundf(input * 100);
),然后对其余的计算使用整数算术。
完成此操作后,您的程序将开始产生结果,并且您将需要重新考虑所拥有的while
和if
结构,如一些注释中所述。