C上的无限do-while循环(2个条件)

时间:2018-09-16 02:01:13

标签: c infinite-loop do-while

在我用C语言编写的程序的这一部分中,Do-While变为无限。我试图做一个
循环播放某人想要键入字符串而不是数字值的情况。

int main(){
    int cnotas;

    do{
    printf("\nIngrese la Cantidad de Notas del Estudiante\n--------------------------------------------\n");    //asks for the number of grades that are going to be used in the average calculation

    if(cnotas>=1){    //if statement to break the loop when the amount of grades is 1 or more
        break;
    }

    }while(scanf("%d", &cnotas)==0 && cnotas<1);    \\gets the cnotas value and checks if is valid
    promedioe(cnotas);
    system("pause");
}

已更新!

忘记提及我要拒绝用户的非数字输入,因此程序不会崩溃。

2 个答案:

答案 0 :(得分:0)

  • 在此语句中:while(scanf("%d", &cnotas)==0 && cnotas<1);您期望用户没有输入任何输入,因为scanf返回否。的输入已成功读取。同时,您期望输入值小于1。

  • cnotasauto变量,因此其起始值可以是任意值,请对其进行初始化。

  • 更好地做到:}while(scanf(" %d",&cnotas)==1 && cnotas<1);

  • 除了所有这些之外,您还使用错误的标签\\而不是//写了评论。

答案 1 :(得分:0)

考虑您想做什么。您想读取输入,直到读取的值小于1。

#include <stdlib.h>

int main(){
    int cnotas;
    do {
         printf("\nIngrese la Cantidad de Notas del Estudiante\n--------------------------------------------\n");    //asks for the number of grades that are going to be used in the average calculation

        // Read the input...
        if (scanf("%d", &cnotas) != 1) {
              fprintf(stderr, "scanf error!\n");
              exit(-1);
        }
        // ...until the input is lower then 1    
    } while (cnotas < 1);
    promedioe(cnotas);
    system("pause");
}