【问题标题】:Indefinite for loop not working in C无限循环在 C 中不起作用
【发布时间】:2013-06-25 18:04:31
【问题描述】:

我目前正在阅读 Ivor Horton 的《Beginning C》。无论如何,我不确定的for 正在打印我的printf 声明两次,然后再继续。我确定我做错了什么,但我直接从书中复制了代码。如果这很重要,我正在使用 Dev-C++。这是代码...谢谢

#include <stdio.h>
#include <ctype.h>  // For tolower() function  //

int main(void)
{
char answer = 'N';
double total = 0.0;  // Total of values entered //
double value = 0.0;  // Value entered //
int count = 0;

printf("This program calculates the average of"
                       " any number of values.");
for( ;; )
{
    printf("\nEnter a value: ");
    scanf("%lf", &value);
    total+=value;
    ++count;

    printf("Do you want to enter another value? (Y or N): ");
    scanf("%c", &answer);

    if(tolower(answer) == 'n')
        break;
}

printf("The average is %.2lf.", total/count);
return 0;
}

【问题讨论】:

  • 看起来不错:codepad.org/05iK44DP
  • 此程序计算任意数量值的平均值。输入一个值:5 你想输入另一个值吗?(Y 或 N):输入一个值:如你所见,它直接跳过了 scanf,我不知道为什么......再次感谢
  • answer 的值默认为'N',我不熟悉scanf() 但如果由于某种原因它没有覆盖变量,则循环中断条件将为真。
  • C 的经验法则。它永远不是编译器。永远。
  • 有趣的是我的书已经有 150 页了,这是我第一次搞砸了。

标签: c dev-c++


【解决方案1】:

如果我们简单地运行您的程序,将会发生以下情况:

  1. 它提示用户输入一个数字。
  2. 用户输入一个数字并按下回车键。
  3. scanf 读取数字,但将换行符留在队列中。
  4. 它提示用户输入 Y 或 N。
  5. 它会尝试读取一个字符,但不会跳过任何空格/换行符,因此最终会消耗队列中留下的换行符。

显然,我们需要跳过换行符。幸运的是,这很容易,如果不是很明显:在格式字符串的开头添加一个空格,例如:

scanf(" %c", &answer);

格式字符串中的空格表示“在阅读下一个内容之前尽可能多地跳过空格”。对于大多数转换,这是自动完成的,但不是字符串或字符。

【讨论】:

  • 不应该跳过它读取数字的第一个scanf吗?
  • @Havenard:哎呀,我错过了,但问题仍然存在:读取数字只会跳过足够的空格以到达数字的开头。读取数字后,空格仍然存在。
  • 哇。太感谢了!我什至没有意识到空间很重要。
【解决方案2】:

改变这一行

scanf("%c", &answer);

scanf(" %c", &answer);

空格会导致 scanf 忽略您输入的字符前面的空格。

空格是在提供数字后按 Enter 键的结果。

【讨论】:

    【解决方案3】:

    代码很好,唯一遗漏的是fflush(stdin);在scanf 函数之前。 它可以始终在scanf 函数之前使用,以避免这些陷阱。 按下“Enter”键的动作将换行符“\n”作为标准输入缓冲区的输入。因此循环中的第一个 scanf 函数将其假定为输入,并且不等待用户键入值。

    #include <stdio.h>
    #include <ctype.h>  // For tolower() function  //
    
    int main(void)
    {
    char answer = 'N';
    double total = 0.0;  // Total of values entered //
    double value = 0.0;  // Value entered //
    int count = 0;
    
    printf("This program calculates the average of"
                           " any number of values.");
    while(1)
    {
        printf("\nEnter a value: ");
        fflush(stdin);
        scanf("%lf", &value);
        total+=value;
        ++count;
    
        printf("Do you want to enter another value? (Y or N): ");
        fflush(stdin);
        scanf("%c", &answer);
        if(tolower(answer) == 'n')
            break;
    }
    
    printf("The average is %.2lf.", total/count);
    getch();
    return 0;
    }
    

    如果您使用控制台,还可以添加getch() 函数来查看结果。

    【讨论】:

    • fflush(stdin) 导致未定义的行为。
    猜你喜欢
    • 1970-01-01
    • 2013-05-30
    • 2016-04-19
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    相关资源
    最近更新 更多