zoukankan      html  css  js  c++  java
  • 联合体

    1.联合:计算机为其中最大的字段分配空间。

    例如:

    typedef union
    {
      short count;
      float weight;
      float volume;
    }quantity;     //占4字节

    2.设置联合的值

    C89方式(保存第一个字段的值):quantity q = {4};  注意加上{}

    指定初始化器(按名设置联合字段的值):quantity q = {.weight=1.5}; 也能设置结构字段的初值

    点表示法:  quantity q;

           q.volume = 3.7;

    3.结构体常和联合体一起使用

     例如:

    typedef union
    {
        float lemon;
        int lime_pieces;
    }lemon_lime;
    
    typedef struct
    {
        float tequila;
        float cointreau;
        lemon_lime citrus;
    }margarita;
    
    margarita m = {2.0,1.0,{0.5}};
    margarita b = {2.0,1.0,{.line_pieces=1}};

    4.枚举

    enum colors {red,green,puce};

    enum colors favorite = puce;

    5.结构和联合用分号分割数据项,而枚举用逗号

    练习(枚举)

    #include <stdio.h>
    
    typedef enum
    {
        COUNT,POUNDS,PINTS
    }unit_of_measure;
    
    typedef union
    {
        short count;
        float weight;
        float volume;
    }quantity;
    
    typedef struct
    {
        const char *name;
        const char *country;
        quantity amount;
        unit_of_measure units;
    }fruit_order;
    
    void display(fruit_order order)
    {
        printf("This order contains");
        if(order.units == PINTS)
            printf("%2.2f pints of %s
    ",order.amount.volume,order.name);
        else if (order.units == POUNDS)
            printf("%2.2f lbs of %s
    ",order.amount.weight,order.name);
        else
            printf("%i %s
    ",order.amount.count,order.name);
    }
    
    int main()
    {
        fruit_order apples = {"apples","England",.amount.count=144,COUNT};
        fruit_order strawberries = {"strawberries","Spain",.amount.weight=17.6,POUNDS};
        fruit_order oj = {"orange juice","U.S.A",.amount.volume=10.5,PINTS};
        display(apples);
        display(strawberries);
        display(oj);
        return 0;
    }
  • 相关阅读:
    1093 Count PAT's(25 分)
    1089 Insert or Merge(25 分)
    1088 Rational Arithmetic(20 分)
    1081 Rational Sum(20 分)
    1069 The Black Hole of Numbers(20 分)
    1059 Prime Factors(25 分)
    1050 String Subtraction (20)
    根据生日计算员工年龄
    动态获取当前日期和时间
    对计数结果进行4舍5入
  • 原文地址:https://www.cnblogs.com/syyy/p/5700917.html
Copyright © 2011-2022 走看看