1、代码简介
① 结构体包含学生的三类信息:年龄,成绩,姓名;
② func函数用于求和各科成绩,并返回总分最高的学生的结构体数据;
③ 关键:用指针等效数组;用结构体指针返回结构体类型数据。
2、代码
① main.cpp
#include <iostream>
#include <string>
#include <cstdio>
#include "func.h"
using namespace std;
//学生信息赋值
int age1 = 10;
double scores1[3] = {122.2, 123.2, 94.8};
string name1 = "zhangsan";
int age2 = 11;
double scores2[3] = {112.9, 203.2, 114.8};
string name2 = "lisi";
student zhangsan = {age1, scores1, name1};
student lisi = {age2, scores2, name2};
//定义一个student结构体指针,用于接收函数运行后返回的结果
student *get_answer;
int main()
{
get_answer = brilliant(zhangsan, lisi);
cout << get_answer->name << " is more brilliant" << endl;
return 0;
}
② func.cpp
#include "func.h"
student *brilliant(student A_people, student B_people)
{
student *answer_people; //定义一个student结构体类型的指针,返回函数运算结果
double A_total_scores, B_total_scores; //定义两个变量,代表两位同学的总分
A_total_scores = A_people.scores[0] + A_people.scores[1] + A_people.scores[2];
B_total_scores = B_people.scores[0] + B_people.scores[1] + B_people.scores[2];
if (A_total_scores >= B_total_scores)
{
answer_people = &A_people;
}
else
{
answer_people = &B_people;
}
return answer_people;
}
③ func.h
#include <string>
using namespace std;
typedef struct
{
int age; //年龄
double *scores; //分数,由于是多科成绩,所以此处定义一个指针,后续以数组赋值的方式将成绩传入该指针
string name; //姓名
} student;
extern student *brilliant(student A_people, student B_people);
当然,也可以的将上面三个文件汇总成一个main文件:
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
typedef struct
{
int age; //年龄
double *scores; //分数,由于是多科成绩,所以此处定义一个指针,后续以数组赋值的方式将成绩传入该指针
string name; //姓名
} student;
//学生信息赋值
int age1 = 10;
double scores1[3] = {122.2, 123.2, 94.8};
string name1 = "zhangsan";
int age2 = 11;
double scores2[3] = {112.9, 203.2, 114.8};
string name2 = "lisi";
student zhangsan = {age1, scores1, name1};
student lisi = {age2, scores2, name2};
//定义一个student结构体指针,用于接收函数运行后返回的结果
student *get_answer;
student *brilliant(student A_people, student B_people)
{
student *answer_people; //定义一个student结构体类型的指针,返回函数运算结果
double A_total_scores, B_total_scores; //定义两个变量,代表两位同学的总分
A_total_scores = A_people.scores[0] + A_people.scores[1] + A_people.scores[2];
B_total_scores = B_people.scores[0] + B_people.scores[1] + B_people.scores[2];
if (A_total_scores >= B_total_scores)
{
answer_people = &A_people;
}
else
{
answer_people = &B_people;
}
return answer_people;
}
int main()
{
get_answer = brilliant(zhangsan, lisi);
cout << get_answer->name << " is more brilliant" << endl;
return 0;
}