【问题标题】:Issue with for loop and scanf in c language [duplicate]c语言中的for循环和scanf问题[重复]
【发布时间】:2016-06-09 08:54:07
【问题描述】:

我正在尝试制作一个简单的程序来计算平均 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

【问题讨论】:

  • 您应该打印cYesNo 的值,以确定其中的内容。
  • '\n' != 'y', 'y' 不是要转换的有效浮点数。
  • 你确实意识到整个区块 else if(cYesNo == 'n' || cYesNo == 'N') continue; 什么都不做,是吗?
  • @Lundin:如果您要对程序进行总体评价,为什么不提一下可能的浮点除零以及循环中累加器的归零?

标签: c for-loop scanf


【解决方案1】:

原因: 这是由于空格导致的

    scanf("%f", &fUserInput);

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


解决方案:

通过在扫描cYesNo 时在%c 之前留一个空格来使用任何空格来避免这种情况

    scanf(" %c", &cYesNo);

为什么要给空间?

通过给出一个空格,编译器从 以前的scanf()


建议

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

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

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

例如:

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

这样您就可以知道正在扫描到字符中的内容,如果是whitespace,请通过上述方法避免它:)

【讨论】:

  • 感谢@Cherubim Anand
【解决方案2】:

你需要更换

scanf("%c", &cYesNo);

通过

scanf(" %c", &cYesNo);

原因在此详述:How to do scanf for single char in C

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多