C 语言中,定义结构体(struct)是一种组织数据的有效方式。时间结构体可以用来表示时、分、秒等时间信息,学生结构体可以用来存储学生的基本信息,复数结构体可以用来表示复数。

1、 时间结构体(Time)

时间结构体可以用来表示时、分、秒等时间信息,代码如下,

#include <stdio.h>

// 定义时间结构体 
typedef struct {
    int year;      // 年份 
    int month;     // 月份 
    int day;       // 日期 
} Time;
 
// 输出时间结构体 
void printTime(Time time) {
    printf("年份: %d, 月份: %d, 日期: %d\n", time.year,  time.month,  time.day); 
}
 
int main() {
    // 定义时间结构体变量 
    Time now = {2023, 8, 7};
    
    // 输出时间 
    printTime(now);
    
    return 0;
}

2、复数结构体(Complex)

复数结构体可以用来表示复数,包括实部和虚部,代码如下,

#include <stdio.h>

// 定义复数结构体 
typedef struct {
    double real; // 实部 
    double imag; // 虚部 
} Complex;
 
// 输出复数结构体 
void printComplex(Complex complex) {
    printf("实部: %.2f, 虚部: %.2f\n", complex.real,  complex.imag); 
}
 
int main() {
    // 定义复数结构体变量 
    Complex num = {5.5, 3.7};
    
    // 输出复数 
    printComplex(num);
    
    return 0;
}

3、学生结构体(Student)

学生结构体可以用来存储学生的基本信息,如姓名、年龄、成绩等,代码如下,

#include <stdio.h>

// 定义学生结构体 
typedef struct {
    char name[50];  // 学生姓名 
    int age;        // 年龄 
    float score[3]; // 三门课程的成绩 
} Student;
 
// 输出学生结构体 
void printStudent(Student student) {
    printf("学生姓名: %s, 年龄 : %d, 三门课程的成绩: %.1f, %.1f, %.1f\n", student.name,  student.age,  student.score[0],  student.score[1],  student.score[2]); 
}
 
int main() {
    // 定义学生结构体变量 
    Student stu = {"亮亮", 20, {85, 92, 88}};
    
    // 输出学生 
    printStudent(stu);
    
    return 0;
}

4、结构体使用示例

参考上面定义的结构体,赋值修改的使用示例如下,

#include <stdio.h>

// 时间结构体定义
struct Time {
    int hours;
    int minutes;
    int seconds;
};

// 学生结构体定义
struct Student {
    char name[50];
    int age;
    float grade;
};

// 复数结构体定义
struct Complex {
    float real;   // 实部
    float imaginary;   // 虚部
};

int main() {
    // 使用时间结构体
    struct Time time1 = {10, 30, 45};
    printf("Time: %02d:%02d:%02d\n", time1.hours, time1.minutes, time1.seconds);

    // 使用学生结构体
    struct Student student1 = {"Alice", 20, 85.5};
    printf("Student: %s, Age: %d, Grade: %.2f\n", student1.name, student1.age, student1.grade);

    // 使用复数结构体
    struct Complex complex1 = {2.5, -3.7};
    printf("Complex number: %.1f + %.1fi\n", complex1.real, complex1.imaginary);

    // 修改结构体成员的值
    time1.hours = 12;
    student1.grade = 90.0;
    complex1.real = 1.0;
    complex1.imaginary = 2.0;

    // 打印修改后的值
    printf("\nModified values:\n");
    printf("Time: %02d:%02d:%02d\n", time1.hours, time1.minutes, time1.seconds);
    printf("Student: %s, Age: %d, Grade: %.2f\n", student1.name, student1.age, student1.grade);
    printf("Complex number: %.1f + %.1fi\n", complex1.real, complex1.imaginary);

    return 0;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表