如何解决CS50 Pset1现金代码无法正常工作
所以我刚开始学习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);
}
}
解决方法
您将打印方法置于while循环内,如果其条件的计算结果为false,则不会执行其主体。
发生的事情是什么都不会打印,除非cents
到达最后一个while循环时会大于或等于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循环,都将执行print方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。