0

Cに入ったばかりで、問題が発生しています。このwhileループが繰り返されない理由を理解するのに時間がかかっています。JavaScriptで同じループを作成すると、適切な出力が繰り返されます。http://jsfiddle.net/rFghh/

使用するwhile (cents >= 25)と、ターミナルは開始コインを印刷し、点滅するだけでハングします。<=25(以下のように)使用すると、1回の反復が出力されます。私が間違っていることについて何か考えはありますか?

/**
 * 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): 
4

3 に答える 3

8

コードはあなたが思っていることをしません。この行:

while (cents <= 25);
{ ::: }

これと同等です:

while (cents <= 25)
{
    ;
}
{ ::: }

そのため、変更されることのない空のステートメントの実行が永久に繰り返されますcents。セミコロンを削除し、ロジックを再評価して修正します。

于 2013-01-18T20:17:24.433 に答える
7

ステートメントの最後にセミコロンがありますwhile:-

while (cents <= 25);  <-- Here's the semi-colon. Remove it.
于 2013-01-18T20:17:11.327 に答える
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++;
}
于 2013-01-18T20:27:04.183 に答える