首页 > 其他 > 详细

[C]struct, union的结合

时间:2020-07-09 23:52:46      阅读:91      评论:0      收藏:0      [点我收藏+]

 

#include <stdio.h>
typedef union {
    double math;
    double phys;
    double chem;
} Score;

typedef struct student {
    char name[10];
    int age;
    Score grade;
    char whichSubject;
} Student;

void input(Student *s) {
    printf("input your name: ");
    scanf("%s", s->name);
    printf("input your age: ");
    scanf("%d", &s->age);
    printf("which subject m/p/c: ");
    scanf(" %c", &s->whichSubject); //<<这里注意" %c"前有个空格哦
    switch (s->whichSubject) {
        case m: scanf("%lf", &s->grade.math); break;
        case p: scanf("%lf", &s->grade.phys); break;
        case c: scanf("%lf", &s->grade.chem); break;
    }
}

void print(Student *s) {
    switch (s->whichSubject) {
        case m: printf("My name is %s, and I‘m %d. I got %f in Math\n", s->name, s->age, s->grade.math); break;
        case p: printf("My name is %s, and I‘m %d. I got %f in Physics\n", s->name, s->age, s->grade.phys); break;
        case c: printf("My name is %s, and I‘m %d. I got %f in Chemistry\n", s->name, s->age, s->grade.chem); break;
    }
}

int main( )
{
    Student s1;
    input(&s1);
    print(&s1);
    return 0;
}

 

[C]struct, union的结合

原文:https://www.cnblogs.com/profesor/p/13276721.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!