Search code examples
c++functionstructurecall

How to call a function with structure (C++)


My code is not working because I have a problem with the call of my two functions when I use a structure. I think I didn't call it correctly but I'm not sure if the problem is here or in the definition itself. Here is my code:

#include <stdio.h>
#define NUM 3

    struct student{
        char name[20];
        int kor;
        int math;
        int eng;
        int sum;
        double avg;
        double avg2;
        double k, m, e;
};

void average(student* st)
{
    int i, sum = 0;
    for(i=0;i<NUM;i++) {
    st[i].sum= st[i].kor + st[i].math + st[i].eng;
    st[i].avg= st[i].sum / NUM;
    }
}

void average2(student* st)
{
    int i, sum = 0;
    double K, M, E;
    for(i=0;i<NUM;i++) {
        K+= st[i].kor;
        M+= st[i].math;
        E+= st[i].eng;
    }
}

int main(void)
{
    student stu[NUM]={{"Tom"},{"Jane"},{"Eddy"}} ;
    int i;
    int max;
    double K, M, E;
    printf("Input scores.\n");
    for(i=0;i<NUM;i++)
    {   printf("\n<%s>\n",stu[i].name);
        printf("Korean:");
        scanf("%d",&stu[i].kor);
        printf("Math:");
        scanf("%d",&stu[i].math);
        printf("English:");
        scanf("%d",&stu[i].eng);
    }
    printf("\nName\tKorean\tMath\tEnglish\tSum\tAverage\n");
    average(stu);
    for(i=0;i<NUM;i++)
        printf("%s\t%d\t%d\t%d\t%d\t%.2f\n",stu[i].name,stu[i].kor,stu[i].math,stu[i].eng,stu[i].sum,stu[i].avg);

    average2(stu);
    printf("Average %.2lf\t%.2lf%.2lf\n", k/3, m/3, e/3);
}

Thank you in advance for your answers, Coco


Solution

  • for loops should have { and } to enclose more than one line in c++.

    for(i=0;i<NUM;i++)
    {
        st[i].sum= st[i].kor + st[i].math + st[i].eng;
        st[i].avg= st[i].sum / NUM;
    }
    

    Also in your function average2 it is not clear what you are exactly doing.

    You are declaring same variable in main and average2 double K, M, E; so the function will take local variable only.

    For your second printf here is the logic.,

    for(i=0;i<NUM;i++) {
        K+= st[i].kor;
        M+= st[i].math;
        E+= st[i].eng;
    }
    printf("Average %.2lf\t%.2lf%.2lf\n", K/3, M/3, E/3);