【问题标题】:Why is my while loop not repeating in C?为什么我的 while 循环不在 C 中重复?
【发布时间】:2013-01-18 20:15:39
【问题描述】:

我刚刚进入 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): 

【问题讨论】:

  • 删除; 之后的while(...)
  • 您将前往 K&R C 的副本。现在。
  • @H2CO3 ,你会推荐 K&R C 而不是 C 吗?顺便说一句,额外的分号是一个错字 =)
  • @SkinnyG33k 我主要推荐谷歌搜索“C 教程”。

标签: c loops while-loop cs50


【解决方案1】:

代码并没有按照您的想法执行。这一行:

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

等价于:

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

所以这将永远迭代执行一个永远不会改变centsempty-statement。通过删除分号并重新评估您的逻辑来修复它。

【讨论】:

  • 好吧,它永远不会或无限地迭代,因为cents的值在循环中没有改变。
  • 此外,OP 的代码中的逻辑无论如何都存在缺陷。他基本上写道“当美分小于 25 时,减少它”。没有任何意义。
  • 啊……错字……谢谢!我想知道为什么它没有打印任何东西! @H2CO3,正确,它最初是“虽然美分超过 25”,但它只是挂起,并在 lte 25 时打印了一次。
【解决方案2】:

while 语句末尾有一个分号:-

while (cents <= 25);  <-- Here's the semi-colon. Remove it.

【讨论】:

    【解决方案3】:

    您的季度支票需要修正。这实际上应该是一个单独的函数,但快速解决方法是:

    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++;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 2012-11-07
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2011-02-07
      相关资源
      最近更新 更多