温馨提示×

C语言怎么使用结构体输出学生信息

小亿
148
2024-01-09 16:44:52
栏目: 编程语言

我们可以使用结构体来定义学生的信息,然后使用printf函数来输出学生的信息。

首先,我们需要定义一个学生的结构体,包含学生的姓名、年龄和成绩等信息:

struct Student {
    char name[100];
    int age;
    float score;
};

然后,我们可以创建一个学生的结构体变量,并为其赋值:

struct Student student1;
strcpy(student1.name, "张三");
student1.age = 18;
student1.score = 90.5;

最后,我们可以使用printf函数输出学生的信息:

printf("姓名:%s\n", student1.name);
printf("年龄:%d\n", student1.age);
printf("成绩:%.2f\n", student1.score);

完整的代码如下:

#include <stdio.h>
#include <string.h>

struct Student {
    char name[100];
    int age;
    float score;
};

int main() {
    struct Student student1;
    strcpy(student1.name, "张三");
    student1.age = 18;
    student1.score = 90.5;

    printf("姓名:%s\n", student1.name);
    printf("年龄:%d\n", student1.age);
    printf("成绩:%.2f\n", student1.score);
    
    return 0;
}

输出结果为:

姓名:张三
年龄:18
成绩:90.50

1