【问题标题】:How to pass the nested struct array to the function as a parameter?如何将嵌套结构数组作为参数传递给函数?
【发布时间】:2019-10-05 13:53:12
【问题描述】:

我有一个名为 Class 和 Student 的 2 个结构。我想通过访问 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] 的东西,但它们没有用。

【问题讨论】:

  • 你好!请发布显示问题的Minimal, Complete, and Verifiable example。这也应该显示您正在使用的#include 文件。很难阅读双倍行距或三倍行距的代码片段,或者编译它们。

标签: c arrays function struct


【解决方案1】:

您可以像这样计算平均成绩,就像您的程序一样。请注意,我在函数调用中添加了学生的数量,但是您的类型 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;
}     

程序输出:

物理平均成绩为 70.00

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多