在C++语言中,用类函数存储结构数组
时间: 2023-05-25 20:01:35 浏览: 84
的方式是什么?
A: 在 C 语言中,可以使用类函数(也叫做结构体函数或者方法)来操作存储在结构数组中的数据。具体的实现方式包括:
1. 定义结构体类型:
```
typedef struct{
int id;
char name[20];
float score;
}Student;
```
2. 定义结构体函数:
```
void showScore(Student stu){
printf("id: %d\n",stu.id);
printf("name: %s\n",stu.name);
printf("score: %f\n",stu.score);
}
float getAvgScore(Student arr[],int len){
float sum = 0;
int i;
for(i=0;i<len;i++){
sum += arr[i].score;
}
return sum/len;
}
```
3. 在主函数中使用结构体数组和结构体函数:
```
int main(){
Student stuArr[3];
stuArr[0].id=1;
strcpy(stuArr[0].name,"Tom");
stuArr[0].score=80.0;
stuArr[1].id=2;
strcpy(stuArr[1].name,"Jerry");
stuArr[1].score=90.0;
stuArr[2].id=3;
strcpy(stuArr[2].name,"Marry");
stuArr[2].score=85.0;
int len = 3;
int i;
for(i=0;i<len;i++){
showScore(stuArr[i]);
}
printf("average score: %f\n",getAvgScore(stuArr,len));
return 0;
}
```
通过这种方式,可以方便地对结构体数组中的数据进行处理和操作,使得代码更加简洁和易读。