Jonas Bo
Jonas Bo

Reputation: 135

How can I make a function that calculates my grades?

When I try to compile I get this error: conflicting types for 'compute_GPA'.

My main function tests compute_GPA and compute_GPA sholuld calculate the average of the grades!

What have I declared wrong? Here is my code:

#include <stdio.h>
#include <ctype.h>   /* for access to the toupper function */

/* Test a function that calculates the average of grades in a char array. main tests the function */

int main(void)
{
    char a[5] = {'A','C','B','C','D'};
    float see = compute_GPA(a, 5);
    printf("largest = %f", see);  
    return 0;
}

float compute_GPA(char grades[], int n)
{
    float sum = 0;
    int i;
    float count = 0;
    /*Iterate over the array of chars */
    for (i = 0; i < n; i++)
    {
        count++;
        /*Check what char array contain*/
        char check = grades[i];
        switch(toupper(check)) {
            case 'A': sum += 4; break;
            case 'B': sum += 3; break;
            case 'C': sum += 2; break;
            case 'D': sum += 1; break;
            default:sum += 0; break;
        }
    }
    return sum / count;
}

Upvotes: 0

Views: 249

Answers (2)

udit043
udit043

Reputation: 1620

Write

float compute_GPA(char grades[], int n);

Before int main and inside int main write

float see;see = compute_GPA(a,5);

sometimes initialization and assignment in one line creates problem

Upvotes: 0

P.P
P.P

Reputation: 121407

Move the function compute_GPA() definition above main() or

Declare a prototype for it before main():

float compute_GPA(char*, int);

In pre-C99, the compiler assumes a function would return an int if it can't see the declaration. But this implicit declaration conflicts with the actual definition of compute_GPA(). But this "implicit int" rule has been removed from C99 and later. Thus your code is invalid in modern C.

Upvotes: 1

Related Questions