我有 2 个名为 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]
,但它们不起作用。
最佳答案
你可以像这样计算平均成绩,就像你的程序一样。请注意,我在函数调用中添加了学生人数,但您的类型 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
关于c - 如何将嵌套结构体数组作为参数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199840/