无限循环不能在C中工​​作

时间:2013-06-28 03:19:21

标签: c dev-c++

我目前正在阅读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;
}

3 个答案:

答案 0 :(得分:6)

如果我们简要介绍一下你的程序,接下来会发生什么:

  1. 提示用户输入数字。
  2. 用户输入一个号码并按回车。
  3. scanf读取数字,但将换行符留在队列中。
  4. 提示用户键入Y或N。
  5. 它尝试读取一个字符,但不会跳过任何空格/换行符,因此它最终消耗了队列中留下的换行符。
  6. 显然,我们需要跳过换行符。幸运的是,这很容易,如果不明显:在格式字符串的开头添加一个空格,例如:

    scanf(" %c", &answer);
    

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

答案 1 :(得分:2)

更改此行

scanf("%c", &answer);

scanf(" %c", &answer);

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

在提供号码后,空格是敲击Enter的结果。

答案 2 :(得分:-1)

代码很好,唯一遗漏的是fflush(stdin);在scanf函数之前。 它可以在scanf函数之前使用,以避免这些陷阱。 按“Enter”键的动作将新行字符'\ n'作为stdin缓冲区的输入。因此,循环中的第一个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()功能来查看结果。