0

I'm doing my homework and one of the problem really get me confused, the problem is as follows, You need to write a program which calculates the average score of a student, the user inputs 12 scores representing scores of 12 tests. After completing the inputs, the program chooses the highest 10 scores and calculates the average score(round off) of the 10 tests and checks whether the student passes. If the student misses one of the exams, the input will be "none"

I've completed most of the program, what confused me is how to let the program accept both an integer and "none". Here is what I have written.

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    int a[12],i,s,b,sum=0;
    double avg;
    for(i=0;i<12;i++){
        scanf("%d",&a[i]);
    }
    for(i=0;i<12;i++){
        for(s=0;s<i;s++){
            if(a[i]>a[s]){
                b=a[s];
                a[s]=a[i];
                a[i]=b;
            }
        }
    }
    for(i=0;i<10;i++){
        sum+=a[i];
    }
    avg=(double)sum/10;
    avg=(int)(avg+0.5);
    if(avg>=60){
        printf("%.0f\n",avg);
        printf("pass");
    }
    else{
        printf("%.0f\n",avg);
        printf("fail");
    }
    return 0;
}

If I input 12 integers into the program, the answer will be correct, but if I input "none", the program stops me from keeping inputting. I want the program to accept both integer and "none" at any time I want and turn "none" into 0.

FunCry
  • 23
  • 4
  • 3
    `char a[12]` and `scanf("%d",&a[i])` doesn't make any sense. The `%d` format reads an `int` (which is usually four bytes big) but `&a[i]` points to a single `char` (which is usually only a single byte). If you want to get either a string or a number, [*read a string*](https://en.cppreference.com/w/c/io/fgets) and then attempt to [convert it to an integer](https://en.cppreference.com/w/c/string/byte/strtol). – Some programmer dude Oct 26 '19 at 09:48
  • Do not use `scanf()`, Research `fgets()` to read input as a _string_ and then process that. – chux - Reinstate Monica Oct 26 '19 at 10:18
  • Either read a string using `%s` and then convert to int using `atoi` or the like, or abandon `scanf` altogether. See [What can I use for input conversion instead of scanf?](https://stackoverflow.com/questions/58403537/what-can-i-use-to-parse-input-instead-of-scanf) – Steve Summit Oct 26 '19 at 12:04
  • If you insist on using `scanf()` look up its return value. It may tell you something. But I support the others. Don't use `scanf()` if possible. – the busybee Oct 26 '19 at 15:34

0 Answers0