简体   繁体   中英

Having problems of skipping loops after scanf

I am in my first year of uni, studying c. I am doing one of my assignment but having problems with one of the loop just skipping. I am using Codeblocks with the GNU GCC compiler. Please ignore option 2, 3, 4.

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

int main()
{
    int num, i, numscr;
    float grade[2021];
    int id[2021];
    int opt;
    float avg[2021];
    float sum=0.0;
    do {
        printf("\nOption 1: Enter student's info\n");
        printf("Option 2: Print out student's info\n");
        printf("Option 3: Find the student with the lowest and highest grade\n");
        printf("Option 4: Exit\n");
        printf("Enter option: ");
        scanf("%d", &opt);
        if(opt==1)
        {
            printf("\n\tEnter the amount of student (Amount>=2): ");
            scanf("%d", &num);
            printf("\tEnter the amount of subject: ");
            scanf("%d",&numscr);
            for(i=0; i<num; i++)
            {
                printf("\n\tEnter student's id: ");
                scanf("%d", &id[i]);
                for(i=1; i<=numscr; i++)
                {
                    printf("\tEnter point of subject %d: " ,i);
                    scanf("%f", &grade[i]); /*The loop skips here.
                    After entering the grade for each subject,
                    it just skips whatever student's id and subject's point there are left.
                    I think the problem is with the sum+=grade[I]; but I don't know why*/
                    sum+= grade[i];
                }
            }
            avg[i]=sum/numscr;
        }
    } while(opt>0 && opt<=3)
    return 0;
}

Sorry if the code doesn't look great, I forgot to format it until now. If anyone can help then I really appreciate it, I've been racking my head for the entirety of the afternoon now.

You used i for both loops of for(i=0; i<num; i++) and for(i=1; i<=numscr; i++) . This means that the inner loop will use i and affect the outer loop.

Use another variable (for example, j ) for the inner loop to fix.

Also it looks like you forgot to initialize sum before calculating the average for each query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM