C 上的无限 do-while 循环(2 个条件)
Infinite do-while loop on C (2 conditions)
在我的 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");
}
已更新!
忘了说我想拒绝用户的非数字输入,所以程序不会崩溃。
在此声明中:while(scanf("%d", &cnotas)==0 && cnotas<1);
您不希望用户输入任何内容,因为 scanf
returns 没有。输入成功读取。同时您期望输入值小于 1.
cnotas
是 auto
变量所以它的起始值可以是任何东西,初始化它。
最好做到:}while(scanf(" %d",&cnotas)==1 && cnotas<1);
除此之外,您在评论中使用了错误的标签 \
而不是 //
。
想想你想做什么。您想读取输入,直到读取的值低于 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");
}
在我的 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");
}
已更新!
忘了说我想拒绝用户的非数字输入,所以程序不会崩溃。
在此声明中:
while(scanf("%d", &cnotas)==0 && cnotas<1);
您不希望用户输入任何内容,因为scanf
returns 没有。输入成功读取。同时您期望输入值小于 1.cnotas
是auto
变量所以它的起始值可以是任何东西,初始化它。最好做到:
}while(scanf(" %d",&cnotas)==1 && cnotas<1);
除此之外,您在评论中使用了错误的标签
\
而不是//
。
想想你想做什么。您想读取输入,直到读取的值低于 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");
}