PYTHON怎么实现类似C里的结构体数组

Python013

PYTHON怎么实现类似C里的结构体数组,第1张

from ctypes import *

class AAA(Structure):

    _fields_ = [("a", c_int),

                ("b", c_int),

                ("c", c_int),

                ("d", c_int),

                ]

那我们首先定义学生结构体类型,然后创建一个大小为5的该结构体数组:

然后我们可以定义三个函数

一个函数用于输入5个学生的数据,这个函数的参数应该是学生结构体数组的指针,因为我们要在函数内部更新学生数据,而不是返回新的数据:

一个函数用于求出每个学生的平均分,这个函数的参数应该是学生结构体的指针,因为我们要在函数内部更新学生的平均分,而不是返回新的平均分:

这是求出平均分最高的学生的函数:

这个函数的参数是学生结构体数组的指针和指向学生结构体的指针的指针,因为我们要在函数内部更新最高平均分的学生的指针。

最后,我们可以在主函数中调用这些函数来完成题目要求的功能:

完整的代码如下:

struct Student {

int student_id

int class_id

char name[100]

int course1

int course2

int course3

float average_score

}

void input_student_data(struct Student* students) {

for (int i = 0i <5i++) {

printf("输入第%d个学生的数据:\n", i + 1)

printf("学号: ")

scanf("%d", &students[i].student_id)

printf("班级: ")

scanf("%d", &students[i].class_id)

printf("姓名: ")

scanf("%s", students[i].name)

printf("课程1: ")

scanf("%d", &students[i].course1)

printf("课程2: ")

scanf("%d", &students[i].course2)

printf("课程3: ")

scanf("%d", &students[i].course3)

}

}

void compute_average_score(struct Student* student) {

student->average_score = (student->course1 + student->course2 + student->course3) / 3.0

}

void find_highest_average_score(struct Student* students, struct Student** highest_average_score_student) {

*highest_average_score_student = &students[0]

for (int i = 1i <5i++) {

if (students[i].average_score >(*highest_average_score_student)->average_score) {

*highest_average_score_student = &students[i]

}

}

}

int main() {

struct Student students[5]

input_student_data(students)

for (int i = 0i <5i++) {

compute_average_score(&students[i])

printf("学生%d的平均分为: %.2f\n", i + 1, students[i].average_score)

}

struct Student* highest_average_score_student

find_highest_average_score(students, &highest_average_score_student)

printf("平均分最高的学生是: \n")

printf("学号: %d\n", highest_average_score_student->student_id)

printf("班级: %d\n", highest_average_score_student->class_id)

printf("姓名: %s\n", highest_average_score_student->name)

printf("课程1: %d\n", highest_average_score_student->course1)

printf("课程2: %d\n", highest_average_score_student->course2) 

printf("课程3: %d\n", highest_average_score_student->course3) 

printf("平均分: %.2f\n", highest_average_score_student->average_score) 

return 0