首页 > 解决方案 > 如何在下面的程序中修改程序以将数组范围设置为 0 到 100

问题描述

我需要下面的代码来识别输入的成绩是低于 1 还是大于 100。如果不在参数范围内,我想让用户知道并允许他们输入另一个成绩而不退出程序或失去他们的成绩已经进入。我不希望程序在用户输入 q 之前退出,并且我想确保当时输入的所有有效成绩都打印出来。我尝试了很多方法,但没有得到正确的结果。我想我可能需要其他一些 if 语句,但我一直无法找到合适的工作。您可以分享任何让我走上正轨的信息,我们将不胜感激。

#include <stdio.h>
#include <stdlib.h>


int main()
{
    char choice;
    int gradeArray[100];
    int grades;
    int gCount=0,i;
    for(gCount=0; gCount<100; gCount++)
    {
        //for loop to read the grades till array size
        printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
        scanf("%c",&choice);
        if(choice == 'a' || 'A')
        {
            //if user choice is a, then read the grade
            printf( "Enter grade: ");
            scanf("%d", &grades);
            getchar();
            gradeArray[gCount] = grades; //add the grade to array
        }
        if(choice == 'q') //if the user choice is q, then exit the loop
        {
            break;
        }
    }
    printf("Grades are:\n");
    for(i=0; i<gCount; i++)
    {
        printf(" %d%%\n", gradeArray[i]); //print grades
    }

    return 0;
}

标签: c

解决方案


您可以执行一个 while 循环来验证用户输入。一段时间后,您将能够强制用户输入正确的成绩。

if(choice == 'A' || choice == 'a'){
    printf("Enter grade:");
    scanf("%d", &grades);
    getchar();
    while(grade < 1 || grade > 100){
        printf("You entered a wrong number\n");
        printf("Enter a grade between 1 and 100: ");
        scanf("%d", &grades);
        getchar();
    }
    gradeArray[gCount] = grades;
}

推荐阅读