C程序限制整数输入范围

时间:2018-07-08 14:02:29

标签: c input integer range

我是一名新的C编程学习者,我正在尝试制作一个程序,该程序将根据成绩输入和科目学分计算学生的GPA。

  1. 我遇到的问题是我想将输入的主题数限制为仅2个到6个。

  2. 另一个问题是我想限制用户只能输入1到100之间的整数,而不是其他任何关键字,特殊字符(EOF)

我已将“ ###”放在注释行中,我需要进行这些修改。

#include <stdio.h>
int main(void) {
    // input      user input -- hopefully a number
    // temp       used to collect garbage characters
    // status     did the user enter a number?
    // counter    for keeping track of loop repetition
    // no         no. of subjects to be entered by user.
    // credits    credits per subject 
    // grades     grades acheived in each subject (1 to 100).
    // grade_value  for holding the value of each subject grade (for ex; 80 to hundred is 4.0)
    // grade_points  Grade points for each subject (credits * grade_value)
    // sum         sum of total grade points
    int counter = 1, subjects, no, credits, grades, status, temp;
    float grade_value, grade_point, sum;
    printf("Enter number of subjects you took for current semester: ");
    status = scanf("%d", & no);

    // ### I want to limit this integer input to be >=2 && <=6.

    while (status != 1) {
        while ((temp = getchar()) != EOF && temp != '\n');
        if ((temp < 2) && (temp > 6));
        break;
        printf("Invalid input... please enter the number of subject again: ");
        status = scanf("%d", & no);

    }
    // ### I want to be this input to block other character inputs than integer from 1 to hundred.
    while (counter <= no) {
        printf("\nEnter Subject %d grades separated with credits \n", counter);
        scanf("%d %d", & grades, & credits);
        if ((grades > 0) && (grades <= 29)) {
            grade_value = 0;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 30) && (grades <= 34)) {
            grade_value = 0.67;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 35) && (grades <= 39)) {
            grade_value = 1;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 40) && (grades <= 44)) {
            grade_value = 1.33;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 45) && (grades <= 49)) {
            grade_value = 1.67;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf(" \nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 50) && (grades <= 54)) {
            grade_value = 2;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 55) && (grades <= 59)) {
            grade_value = 2.33;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 60) && (grades <= 64)) {
            grade_value = 2.67;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 65) && (grades <= 69)) {
            grade_value = 3;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 70) && (grades <= 74)) {
            grade_value = 3.33;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 75) && (grades <= 79)) {
            grade_value = 3.67;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        } else if ((grades >= 80) && (grades <= 100)) {
            grade_value = 4;
            printf("Grade value for subject %d is: %.2f", counter, grade_value);
            grade_point = credits * grade_value;
            printf("\nGrade point for subject %d is: %.2f", counter, grade_point);
            sum = sum + grade_point;
            ++counter;
        }
        // To print a message if user doesnt enter an integer varying from 1 to 100.
        else {
            printf("\n Error Grade input, Please Key in Again. (1 to 100 only.)");
        }
    }
    printf("\n");
    printf("\n");
    printf("\nThe GPA is: %.2f", sum);
    if (sum <= 49) {
        printf("\nYou can register for 2 subjects for next semester.");
    } else if ((sum >= 50) && (sum >= 79)) {
        printf("\nYou can register for 5 subjects for next semester.");
    } else if ((sum >= 80) && (sum <= 100)) {
        printf("\nYou can register for 6 subjects for next semester.");
    }
    printf("\n");
    printf("\n");
    printf("\n_______________________________________________________");
    printf("\nEnd of program");
    return 0;
}

2 个答案:

答案 0 :(得分:0)

do-while循环非常适合需要至少调用一次且可以消除重复代码的循环。读取可能来自键盘的非结构化输入(可能会调用./a.out < text.txt)实际上是很棘手的事情。

幸运的是,C常见问题解答有很多建议,例如http://c-faq.com/stdio/scanfprobs.html。但是,如果没有功能,它将变得非常艰巨。通过有限的测试,我很确定这是读取第一个变量的可靠方法。

#include <stdio.h>  /* fgets sscanf */
#include <stdlib.h> /* EXIT_ printf fprintf */
#include <string.h> /* strlen */

int main(void) {
    int no;
    /* Input number, no \in [2, 6], and make sure that the read cursor is on
     the next line. */
    do {
        char buffer[80];
        size_t len;
        printf("Enter number of subjects you took for current semester, [2, 6]: ");
        /* On the advice of http://c-faq.com/stdio/scanfprobs.html, this reads
         into a buffer first. */
        if(!fgets(buffer, sizeof buffer, stdin)) {
            if(feof(stdin)) {
                fprintf(stderr, "Premature EOF.\n");
            } else {
                /* On IEEE Std 1003.1-2001-conforming systems, this will print
                 a meaningful error. */
                perror("stdin");
            }
            /* Can't really do anything interactive once stdin has a read
             error. */
            return EXIT_FAILURE;
        }
        /* This is always going to be true, but segfaults if not. Paranoid. */
        if(!(len = strlen(buffer))) continue;
        /* Normally fgets stores a '\n' at the end; check. */
        if(buffer[len - 1] != '\n') {
            /* Check if the length of the buffer is big enough to hold input. */
            if(len >= sizeof buffer - 1) {
                int c;
                fprintf(stderr, "Line too long.\n");
                /* Flush whole line. http://c-faq.com/stdio/stdinflush2.html */
                while((c = getchar()) != '\n') {
                    if(c != EOF) continue;
                    if(feof(stdin)) fprintf(stderr, "Premature EOF.\n");
                    else            perror("stdin");
                    return EXIT_FAILURE;
                }
                continue;
            } else {
                /* Non-POSIX lines, eg, file without '\n' terminating. */
                fprintf(stderr, "Note: line without line break detected.\n");
            }
        }
        /* Parse buffer for a number that's between [2, 6]. Ignore the rest. */
        if(sscanf(buffer, "%d", &no) != 1 || no < 2 || no > 6) {
            fprintf(stderr, "Invalid input.\n");
            continue;
        }
        /* Now no \in [2, 6]. */
        printf("no: %d\n", no);
        break;
    } while(1);
    return EXIT_SUCCESS;
}

如果您的老师仅输入格式正确的数字,则可能可以摆脱其中的一部分。

答案 1 :(得分:0)

您的代码有一些语义错误。切勿在{{1​​}}语句后加上分号。您也可以通过间隔代码块来编写更清晰的代码。更好的是,您可以重构一些块并将其封装到函数中。除此之外,请参阅以下解决方案:

对于第一个问题,只需几行代码即可解决。好的做法是,用户在输入输入之前先了解输入的限制:

if

另一个问题可以通过使用Standard C库来解决。只是/* ### I want to limit this integer input to be >=2 && <=6. */ #include <stdio.h> int main() { int no; do { printf("Enter number of subjects you took for current semester (2~6): "); scanf("%d", &no); } while (no < 2 || no > 6); return 0; } #include <string.h>

#include <ctype.h>