c - 循环 "enter student id:"语句

标签 c

#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 位数字),我希望转到下一条语句,但它不断重复相同的问题。

如何解决这个问题?

最佳答案

您的代码有很多问题。

  1. if(count1 = 7) 将值 7 赋给变量 count1,以便使用 if(count1 == 7) 进行比较。
  2. 每次用户输入id时,都需要检查其长度,而不仅仅是第一次。您可以使用某种循环和条件。如果满足该条件(即学生 ID 长度为 7 或 8 位数字),则中断循环并继续。
  3. 每次用户输入新数字时,您都需要重置 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/

相关文章:

c - 扫描目录程序-编译错误

c - 单击后如何删除文本?

c - ANSI C - 获取每个数组的随机词

c++ - 为 OpenCV 的 C++ createTrackbar 运行 C 包装器时出现编译段错误(核心已转储)

c - 尝试比较两个字符串

c - 链表-基本插入函数

c - mman.h 确实导入了 mmap 函数但未能导入 mremap

c - 从链表中查找最大值

c - C语言中如何运行多个for循环?

c - 如何在未对齐的缓冲区中使用结构