我刚刚进入C,我遇到了一些麻烦。 我有一点时间弄清楚为什么这个while循环不会重复。我在JavaScript中创建了相同的循环,并重复输出正确的输出。 http://jsfiddle.net/rFghh/
如果我使用while (cents >= 25)
,则终端打印起始硬币并挂起只是闪烁。如果我使用<=25
(如下所示),则会打印一次迭代。关于我做错了什么的想法?
/**
* Greedy, given a change amount, figures out the min number of coins needed
*/
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(int argc, char const *argv[])
{
// declare variables
int cents = 0;
int coins = 0;
// ask user for amount of money, accepts a float value
// convert input to cents and round to nearest int
printf("O hai! ");
do
{
printf("How much change is owed? ");
cents = round(100 * GetFloat());
// if input is negative then ask again
} while (cents <= 0);
printf("Starting Cents: %d, coins are: %d\n", cents, coins);
// Check if you can use a quarter
while (cents <= 25);
{
printf("Cents before decrement: %d\n", cents);
cents = cents - 25;
printf("Cents after decrement: %d\n", cents);
coins = coins + 1;
}
printf("FINAL Cents: %d, coins are: %d\n", cents, coins);
return 0;
}
jharvard@appliance (~/cs50/Week_1/pset1): make greedy && ./greedy
clang -ggdb3 -O0 -std=c99 -Wall -Werror greedy.c -lcs50 -lm -o greedy
O hai! How much change is owed? 1.25
Starting Cents: 125, coins are: 0
Cents before decrement: 125
Cents after decrement: 100
FINAL Cents: 100, coins are: 1
jharvard@appliance (~/cs50/Week_1/pset1):
答案 0 :(得分:8)
代码没有按照您的想法执行。这一行:
while (cents <= 25);
{ ::: }
相当于:
while (cents <= 25)
{
;
}
{ ::: }
这将永远迭代执行永不改变cents
的空语句。通过删除分号并重新评估逻辑来修复它。
答案 1 :(得分:7)
while
声明末尾有一个分号: -
while (cents <= 25); <-- Here's the semi-colon. Remove it.
答案 2 :(得分:1)
您的季度检查需要修复。这实际上可能是一个单独的功能,但快速修复将是:
while (cents >= 25) //should be greater than or equal to and get rid of semicolon
{
printf("Cents before decrement: %d\n", cents);
cents = cents - 25;
printf("Cents after decrement: %d\n", cents);
coins++;
}