有人可以帮我修复我的while循环吗?它一直在运行

时间:2016-10-10 06:34:11

标签: c

我正在尝试运行下面的代码,但我正在进入一个我无法解决的循环。

应该出现的错误消息然后用户可以输入正确的范围值。

有人可以修复这个无限循环,只有当用户输入的值超出范围时才会出现。

#include<stdio.h>

int main(void) {

    int students, counter, total;
    int marks[40];
    int stdno[40];
    total = 0;  

    printf("       ---=== IPC mark Analyser V2.0 ===---\n");
    printf("Please enter the number of students(between 3 and 40):");
    scanf("%d", &students);

    while (students < 3 || students >40) {
        printf("Invalid number, enter a number between 3 and 40 inclusive:");
        scanf("%d", &students);
    }

    printf("Row   Std No  Mrk\n");
    printf("--- --------- ---\n");

    for (counter = 0; counter < students; counter++) {
        printf("    _________ ___\r");
        printf("%03d ", counter + 1);
        scanf("%09d %3d", &stdno[counter], &marks[counter]);

        while (marks < 0 || marks >100 || stdno < 10000000 || stdno > 999999999) {
            printf("Error: Enter values between 0 and 100 inclusive.\n");
            scanf("%09d %3d", &stdno[counter], &marks[counter]);
        }

        return 0;
    }
}

1 个答案:

答案 0 :(得分:2)

  1. 首先,while (marks < 0 || marks >100 || stdno < 10000000 || stdno > 999999999)的wile循环条件不正确。 marksstdno是数组,无法与数字进行比较。您甚至会收到编译器警告。您需要做的是与数组元素marks[counter]stdno[counter]进行比较。这样就可以根据条件检查在循环中输入的每个值。

  2. while循环应该运行两个语句printfscanf。在当前代码中,while循环每次只执行printf。你需要在两个陈述周围加上大括号{

    while (marks[counter] < 0 || marks[counter] >100 || stdno[counter] < 100000000 || stdno[counter] > 999999999)
    {
        printf("Error: Enter values between 0 and 100 inclusive.\n");
        scanf("%09d %3d", &stdno[counter], &marks[counter]);
    }
    
  3. 您可以通过打印上面相同的数字来进一步改善这一点,以便向用户提供指示。

    while (marks[counter] < 0 || marks[counter] >100 || stdno[counter] < 100000000 || stdno[counter] > 999999999)
    {
        printf("Error: Enter values between 0 and 100 inclusive.\n");
        printf("    _________ __\r");
        printf("%03d ", counter + 1);
        scanf("%09d %3d", &stdno[counter], &marks[counter]);
    }