c - c语言中for循环和scanf的问题

标签 c for-loop scanf

<分区>

我正在尝试编写一个简单的程序来计算平均 GPA,但在输出过程中,语句不会按预期停止。我认为 printf 语句中的缓冲区没有任何问题,因为我在每个句子中都使用了一个新行。例如,这在输出中:

Enter a GPA: 
9
Do you want to calculate the average GPA until now?
Press 'y' for yes or 'n' for no: 
Enter a GPA: 
y
Do you want to calculate the average GPA until now?
Press 'y' for yes or 'n' for no: 
The average GPA is 9.0

如您所见,循环继续并再次打印出问题。

我做错了什么?

这是我的代码:

#include <stdio.h>

int main(void){

    /*************************Variable declarations************************/

    float fGPA;
    float fUserInput = 0;
    float fArray[30];
    int x;
    char cYesNo = '\0';

    /*************************Initialize array********************************/

    for(x = 0; x < 30; x++){

        fGPA = 0;
        printf("Enter a GPA: \n");
        scanf("%f", &fUserInput);
        fArray[x] = fUserInput;
        fGPA += fUserInput;
        printf("Do you want to calculate the average GPA until now?\n");
        printf("Press 'y' for yes or 'n' for no: \n");
        scanf("%c", &cYesNo);

        if(cYesNo == 'y' || cYesNo == 'Y')
            break;
        else if(cYesNo == 'n' || cYesNo == 'N')   
            continue;
    }//End for loop

    printf("The average GPA is %.1f\n", fGPA / x);

}//End main

最佳答案

原因: 发生这种情况是由于空格,即 '\n' 在输入 fUserInput

结束时输入的字符
    scanf("%f", &fUserInput);

这个'\n'scanf("%c", &cYesNo);中的%c消费了


解决方案:

通过在扫描 cYesNo 时在 %c 前留一个空格来避免它

    scanf(" %c", &cYesNo);

Why to give a space?

By giving a space,the compiler consumes the '\n' character or any other white space ('\0','\t' or ' ' ) from the previous scanf()


建议

下次如果你遇到这样的问题......尝试打印字符扫描的ascii值:

printf("%d",(int)cYesNo); //casting char->int

并根据 ascii 表检查你的输出:here

例如:

  • 如果是 ' '//space
  • ,则输出为 32
  • 如果是 '\n'//new-line
  • ,则输出为 10
  • 如果是 '\t'//horizo​​ntal-tab
  • ,则输出为 9

这样你就会知道什么被扫描到字符中,如果它是一个 whitespace 通过上面的方法避免它 :)

关于c - c语言中for循环和scanf的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37721199/

相关文章:

javascript - i 没有在 while 循环中定义

python - 带列表的循环数学

c - 如何在C中使用printf和scanf读写文件?

.a 静态库文件的内容

在嵌套文件夹中编译和运行代码

flutter - 如何从表[Flutter] [Dart]中拆分所有值

c - 尝试通过插入从文件流检索的字符来创建二维数组

c - fscanf ("%s%s", cometd ,组);

日历项目几乎用 C 完成

c++ - 如何编写可以在 Linux 和 Windows 中轻松编译的 C++ 程序?