Quick actions

cmd+k|ctrl+k

Navigation

Languages

共用体变量的访问

Snippet info

Language

C

Visibility

public

Author

qwas

Created

2024-05-10T10:05:56.356988Z

Updated

2024-05-10T17:09:10.421693Z

#include <stdio.h>

union computerInfo
{
  char typename[20];
  float price;
};

/**
 * 共用体
 * 不论共用体在定义时,成员变量列表中有多少项,
 * 在某个确定的时刻,共用体只能存储一个成员
*/
int main()
{
  union computerInfo comp1;
  int type = 0;
  printf("组装机(输入0)或品牌机(输入1)?\n");
  scanf("%d", &type);
  if (type == 0)
  {
    printf("请输入该组装机的价格\n");
    scanf("%f", &comp1.price);
    printf("该组装机的价格是%f\n", comp1.price);
  }
  if (type == 1)
  {
    printf("请输入该品牌机的型号\n");
    scanf("%s", &comp1.typename);
    printf("该品牌机的型号是%s\n", comp1.typename);
  }
}

// 输入 0 3000 
// 或
// 输入 1 dell
INFO