CS50 Pset1 现金代码无法正常工作

CS50 Pset1 cash code not working properly

所以我刚开始学习 cs50 课程,我正在用贪心算法做第一个问题集。当我 运行 程序时它会正确地问问题,当我回答时它不给出输出。我不知道哪里出了问题。 这是代码

#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main (void)

{

float n;
int cents;
int coins = 0;

// Prompt user for amount owed
     do
     {
        n = get_float("Change owed?:");
     }
     while (n < 0);

// convert input into cents
     cents = round(n * 100);

//loop for minimum coins
    while (cents >= 25)
{
    cents = cents - 25;
    coins++;
}
    while (cents >= 10)
{
    cents = cents - 10;
    coins++;
}
    while (cents >= 5)
{
    cents = cents - 5;
    coins++;
}
    while (cents >= 1)
{
    cents = cents - 1;
    coins++;
//Print number of coins
printf("%i\n", coins);
}
}

您的 print 方法位于 while-loop 中,如果其条件评估为 false,则不会执行其主体。

发生的事情是什么都不会打印,除非 cents 在到达最后一个 while-loop 时大于或等于 1。

改变这个:

while (cents >= 1)
{
    cents = cents - 1;
    coins++;
    //Print number of coins
    printf("%i\n", coins);
}

对此:

while (cents >= 1)
{
    cents = cents - 1;
    coins++;
}
//Print number of coins
printf("%i\n", coins);

有了这个改动,不管代码流是否进入最后一个while-loop,print方法都会执行。