bugfix> c > 投稿

My knowledge is limited so bear with me but I am experimenting with creating functions and this is what I got so far but it doesn't. All advice is appreciated! Try to create a function that collects input from the user

#include<stdio.h>
int GetIntFromUser(int grades[5]);
int GetIntFromUser(int grades[5])
{
    int counter = 0;
    int incre = 1;
    while(counter < 4)
    {
        printf("Please enter GPA %d: ",incre);
        scanf("%d",&grades[counter]);
        incre++;
        counter++;
    }
}
int main()
{
    int sum = 0;
    int grades[5];
    int counter = 0;
    printf(GetIntFromUser());
    while(counter < 4)
    {
        sum = sum + grades[counter];
        counter++;
    }
    float gpa = (float)sum/counter;
    printf("The average GPA is %.2f\n",gpa);
    return 0;
}

回答 1 件
  • これを試して:

    #include<stdio.h>
    void GetIntFromUser(int grades[5]); //void since you do not return anything
    void GetIntFromUser(int grades[5])
    {
        int counter = 0;
        int incre = 1;
        while(counter < 4)
        {
            printf("Please enter GPA %d: ",incre);
            scanf("%d",&grades[counter]);
            incre++;
            counter++;
        }
    }
    int main()
    {
        int sum = 0;
        int grades[5];
        int counter = 0;
        GetIntFromUser(grades); // Correct function call
        while(counter < 4)
        {
            sum = sum + grades[counter];
            counter++;
        }
        float gpa = (float)sum/counter;
        printf("The average GPA is %.2f\n",gpa);
        return 0;
    }
    
    

    5つの要素の配列もありますが、使用するのは4つだけです。

あなたの答え