Fedon Kotsakis
Fedon Kotsakis

Reputation: 15

Function gives me a wrong answer

I'm new to C. I've been tasked to run a program that calculates the percentage of students that passed an exam,based on N grade inputs.I don't really understand how functions work in though.This is what I came up with

#include <stdio.h>
#define MAX_N 300
main()

{   
int N,grade,i;

float success(N)
{
    float sum=0.0;
    for (i=0;i<N;i++) {
        if (grade>=5) {
            sum+=1;
        }
        float success=sum/N;
        return(success);
    }
}    

printf("How many students? ");
scanf("%d",&N);
printf("Enter grades(0-10) of %d students ",N);
for (i=0;i<N;i++){
    scanf("%d",&grade);
    
}
printf("%f percent of students have passed the exam ",success(N);
return(0);

} 

It looks like it should work, however I always get the wrong result.It is stuck on displaying 0.2 or 0.25 for any input I give.Can somebody help?

Upvotes: 0

Views: 76

Answers (4)

bekici
bekici

Reputation: 84

I think you should examine the code I wrote. A little bad code. But it can help.

#include <stdio.h>

int students_success(int *);

int main() {
    int n;

    printf("How many students?\n");
    scanf("%d", &n);
    printf("Enter grades(0-10) of %d students\n", n);
    int grade;
    int pass_std = 0;
    for(int i = 0; i < n; ++i) {
        scanf("%d", &grade);
        pass_std = students_success(&grade);
    }
    printf("%.2f percent of students have passed exam.\n", (double)pass_std / n);
}
int students_success(int *grade) {
    static int pass_std = 0;
    if(4 < *grade) {
        ++pass_std;
    }
    return pass_std;
}

Upvotes: 0

dreamers-blog
dreamers-blog

Reputation: 114

grade should be an array of N integers so that each and every value is stored. You also forgot to multiply success by 100 to get the percentage.

I think I fixed the code:

#include <stdio.h>
#define MAX_N 300
float success(int grade[],int N)

{int i;
    float sum=0.0;
    for (i=0;i<N;i++) {
        if (grade[i]>=5) {
            sum+=1;
        }

    }
    float success=sum/N;
    return(success*100);
}

int main(){
int N, i;

printf("How many students? ");
scanf("%d",&N);
int grade[N];
printf("Enter grades(0-10) of %d students ",N);
for(i=0;i<N;i++){
    scanf("%d", &grade[i]);

}
printf("%f percent of students have passed the exam ", success(grade, N));
return(0);

}

Upvotes: 0

AFzal Khan
AFzal Khan

Reputation: 81

I guess you are taking multiple value for grade and not taking array for it. grade should be an array and in loop scanf("%d",&grade[i]); should be implement.

Upvotes: 1

Roshish Parajuli
Roshish Parajuli

Reputation: 11

The problem is that in grade only the last entered data is being stored. Make grade as an array so that all data can be stored.

Upvotes: 1

Related Questions