简体   繁体   中英

In C checking the value of every element and return true or function

Can someone help me or give idea on how can I correct my logic in the array loop

My Problem is I have student quiz scores and perfect quiz scores

My Goal is I want to compare student quiz scores every element to the Perfect quiz scores, where Student scores cannot be negative value or greater than the perfect quiz scores, and if it is inputted negative I just want to reinput it to the value where it is not negative or greater than the quiz scores, but I really have no idea how to do it.

Also I tried creating function for quizScore and input the loop there and if the quiz is either negative or greater than, then I'll just call the quizScore function but it still fails.

void initStudents() {
    printf("\nEnter number of students: ");
    scanf("%d", &studentCount);
    for(int i=0; i < studentCount; i++){
        printf("\n-------------------------------------------------------------------\n");
        printf("\n[Student %d of %d]\n", i + 1,studentCount);
        printf("Enter name of student %d: \n", i + 1);
        scanf("%s",studentNames[i]);
        for(int j = 0; j < qCount; j++){
        printf("\n[Quiz %d of %d] \n", j + 1, qCount);
        printf("Enter score for quiz %d: \n", j + 1);
        scanf("%d", &quiz[j]);
        if(quiz[j] < 0 || quiz[j] > qPerfect[j]) {
            quiz[j] = 0;
        }
        else {
            //no idea what to put here
        }
    }
    printf("\n-------------------------------------------------------------------\n");
    for(int j = 0; j < pCount; j++) {
        printf("\n[Project %d of %d]\n", j + 1, pCount);
        printf("Enter score for project %d: \n", j + 1);
        scanf("%d", &project[j]);
    }
    printf("\n-------------------------------------------------------------------\n");
    for(int j = 0; j < hmCount; j++) {
        printf("\n[Homework %d of %d]\n", j + 1, hmCount);
        printf("Enter score for homework %d: \n", j + 1);
        scanf("%d", &homework[j]);
    }       
}
//end of initstudents

Loop until there's a valid input:

while (true) {
    printf("\n[Quiz %d of %d] \n", j+1, qCount);
    printf("Enter score for quiz %d: \n", j+1);
    scanf("%d",&quiz[j]);

    if (quiz[j] < 0 || quiz[j] > qPerfect[j]) {
        quiz[j] = 0;
    } else {
        break;
    }
}

You can do it using while

while (quiz[j] < 0 || quiz[j] > qPerfect[j]) {
    printf("Invalid score \n");
    printf("Enter score for quiz %d: \n", j + 1);
    scanf("%d", &quiz[j]);
}

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