如何将嵌套的struct数组作为参数传递给函数?

时间:2019-05-18 14:23:10

标签: c arrays function struct

我有两个名为Class和Student的结构。我想通过访问Class结构中的Students [30]数组来计算学生的平均成绩。

这是我的代码:

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

typedef struct Student{
  char name [20] ;
  int grade ;
  int number ;
} Student;

typedef struct Class{
  char className[20] ;
  Student Students[30] ;
} Class;  

double calculateAverageGrade(/* I want to pass the Students[30] array here */ ) {
  int i ;
  int sum = 0 ;
  for(i=0;i<3;i++) {
  }
  return sum/3 ;
}   

int main() {
  Student s1 ={"John",75,758} ;
  Student s2 = {"Jack",85,123} ;
  Student s3 = {"Lisandra",50,321} ;
  Class c1 ={'\0'} ;

  strcpy(c1.className,"Physics") ;

  c1.Students[0] = s1 ;
  c1.Students[1] = s2 ;
  c1.Students[2] = s3 ;

  calculateAverageGrade(/*needs to take Students[30] array*/);
  return 0 ;
}        

我已经尝试过Class Students[30]Class.Student Students[30]这样的东西,但是它们没有用。

1 个答案:

答案 0 :(得分:0)

您可以像计算程序一样,像这样计算平均成绩。请注意,我在函数调用中增加了学生数,但是无论如何您的类型Class都应该包含该数字,最好将Class传递给函数,而不仅仅是传递它包含的数组

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

typedef struct Student{
    char name [20];
    int grade;
    int number;
}Student;

typedef struct Class{
    char className[20];
    Student Students[30];
}Class;  

double calculateAverageGrade(Student *Students, int count) {  // pass the number of students
    int i;
    int sum = 0;
    for(i = 0; i < count; i++) {                 // don't guess the number of students
        sum += Students[i].grade;
    }
    return (double)sum / count;                  // otherwise integer division
}   

int main(void) {
    Student s1 = { "John",     75, 758 };
    Student s2 = { "Jack",     85, 123 };
    Student s3 = { "Lisandra", 50, 321 };
    Class c1 = {'\0'};
    strcpy(c1.className, "Physics");
    c1.Students[0] = s1;
    c1.Students[1] = s2;
    c1.Students[2] = s3;
    printf("The average grade in %s is %.2f\n", c1.className,
            calculateAverageGrade(c1.Students, 3));
return 0;
}     

程序输出:

The average grade in Physics is 70.00

相关问题