面试题答案
一键面试#include <stdio.h>
// 定义结构体
struct Student {
char name[50];
int age;
float score;
};
// 打印结构体信息的函数
void printStudentInfo(struct Student *student) {
printf("姓名: %s\n", student->name);
printf("年龄: %d\n", student->age);
printf("成绩: %.2f\n", student->score);
}
你可以使用以下方式调用这个函数:
int main() {
struct Student student1 = {"张三", 20, 85.5};
printStudentInfo(&student1);
return 0;
}
上述代码中:
- 首先定义了一个
struct Student
结构体,包含name
(字符数组)、age
(整型)和score
(浮点型)三个成员。 - 然后编写了
printStudentInfo
函数,该函数接受一个指向struct Student
结构体的指针,通过指针访问并打印结构体中的信息。 - 在
main
函数中,创建了一个student1
结构体变量并初始化,然后调用printStudentInfo
函数打印其信息。
如果是C++语言,代码如下:
#include <iostream>
#include <string>
// 定义结构体
struct Student {
std::string name;
int age;
float score;
};
// 打印结构体信息的函数
void printStudentInfo(const Student *student) {
std::cout << "姓名: " << student->name << std::endl;
std::cout << "年龄: " << student->age << std::endl;
std::cout << "成绩: " << student->score << std::endl;
}
调用函数方式如下:
int main() {
Student student1 = {"李四", 22, 90.0};
printStudentInfo(&student1);
return 0;
}
在C++代码中:
- 定义
struct Student
结构体,name
使用std::string
类型,相较于C语言的字符数组使用更方便。 printStudentInfo
函数同样接受结构体指针,使用std::cout
输出信息。- 在
main
函数中创建并初始化student1
结构体变量,调用printStudentInfo
函数输出其信息。