2015年4月18日土曜日

開発環境

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

その他参考書籍

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

コード(BBEdit, Emacs)

#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;
  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.amount.volume, order.name);
  else if (order.units == POUNDS)
    printf("%2.2fポンドの%sです\n", order.amount.weight, order.name);
  else
    printf("%ii個の%sです\n", order.amount.count, order.name);
}

int main() {
  fruit_order_s apples = {
      .name = "りんご", .country = "イギリス", .amount.count = 144, COUNT};
  fruit_order_s strawberries = {
      .name = "いちご", .country = "スペイン", .amount.weight = 17.6, POUNDS};
  fruit_order_s oj = {.name = "オレンジジュース",
                      .country = "アメリカ",
                      .amount.volume = 10.5,
                      PINTS};
  fruit_order_s fruits[] = {apples, strawberries, oj};
  for (size_t i = 0; i < 3; i++) display(fruits[i]);  
}
    

入出力結果(Terminal)

p
$ crun.sh sample256
clang ...
この注文位含まれるものは144i個のりんごです
この注文位含まれるものは17.60ポンドのいちごです
この注文位含まれるものは10.50パイントのオレンジジュースです
$

0 コメント:

コメントを投稿