2015年2月5日木曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の5章(構造体、共用体、ビットフィールド: 独自の構造体を使う)、コードマグネット(p.256)を解いてみる。

その他参考書籍

コードマグネット(p.256)

コード(BBEdit, Emacs)

sample256.c

#include <stdio.h>

typedef enum {
  COUNT, POUNDS, PINTS
} unit_of_measure;

typedef union quantity_s {
  short count;
  float weight;
  float volume;
} quantity_s;

typedef struct fruit_order_s {
  const char *name;
  const char *country;
  union {
    union quantity_s;
    quantity_s amount;    
  };
  unit_of_measure units;
} fruit_order_s;

void display (fruit_order_s order){
  printf("この注文に含まれるものは");
  if (order.units == PINTS)
    printf("%2.2fパイントの%sです\n", order.volume, order.name);
  else if (order.units == POUNDS)
    printf("%2.2fポンドの%sです\n", order.weight, order.name);
  else
    printf("%i子の%sです\n", order.count, order.name);
}

int main(){
  fruit_order_s apples = {.name="リンゴ", .country="イギリス",
                          .count=144, .units=COUNT};
  fruit_order_s strawberries = {.name="いちご", .country="スペイン",
                                .weight=17.6, .units=POUNDS};
  fruit_order_s oj = {.name="オレンジジュース", .country="アメリカ",
                      .volume=10.5, .units=PINTS};
  display(apples);
  display(strawberries);
  display(oj);
}
    

入出力結果(Terminal)

$ crun.sh sample256
clang ...
この注文に含まれるものは144子のリンゴです
この注文に含まれるものは17.60ポンドのいちごです
この注文に含まれるものは10.50パイントのオレンジジュースです
$

0 コメント:

コメントを投稿