#include <stdio.h>
#include <stdlib.h>
int main()
{
int id = 0;
int pin = 0;
int count1 = 0;
int count2 = 0;
printf("enter student id: ");
scanf("%i",&id);
while(id !=0)
{
id /= 10;
count1++;
}
while(count1 != 7)
{
printf("the student id should be in 7 or 8 digits\n");
printf("enter student id: ");
scanf("%i",&id);
}
if(count1 = 7)
{
printf("enter student pin: ");
scanf("%i",&pin);
}
return 0;
}
如果我重新输入我的学生 ID(7 位数字),我希望转到下一条语句,但它不断重复相同的问题。
如何解决这个问题?
最佳答案
您的代码有很多问题。
if(count1 = 7)
将值 7 赋给变量 count1,以便使用if(count1 == 7)
进行比较。- 每次用户输入id时,都需要检查其长度,而不仅仅是第一次。您可以使用某种循环和条件。如果满足该条件(即学生 ID 长度为 7 或 8 位数字),则中断循环并继续。
- 每次用户输入新数字时,您都需要重置
count1
,否则您将继续无限增加它。
例如,您可以这样做:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int id = 0;
int pin = 0;
int count1 = 0;
for(;;)
{
printf("enter student id: ");
scanf("%i",&id);
while(id !=0) {
id /= 10;
count1++;
}
if (count1 != 7 && count1 != 8) {
printf("the student id should be in 7 or 8 digits\n");
count1 = 0;
}
else break;
}
printf("enter student pin: ");
scanf("%i",&pin);
return 0;
}
关于c - 循环 "enter student id:"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700670/