開発環境
- OS: macOS High Sierra - Apple
- Text Editor: Emacs
- コンパイラー: LLVM/Clang, GCC(gcc)
- プログラミング言語: C
Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の5章(構造体、共用体、ビットフィールド - 独自の構造を使う)、コードマグネット(p. 256)を取り組んでみる。
コードマグネット(p. 256)
Makefile
CC = cc all: sample run sample: sample.c $(CC) sample.c -o sample run: sample ./sample
コード
#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;
} FruitOrder;
void display(FruitOrder order) {
printf("この注文に含まれるものは");
if (order.units == COUNT) {
printf("%i個の%sです\n", order.amount.count, order.name);
} else if (order.units == POUNDS) {
printf("%2.2fポンドの%sです\n", order.amount.weight, order.name);
} else {
printf("%2.2fパイントの%sです\n", order.amount.volume, order.name);
}
}
int main() {
FruitOrder apples = {"林檎", "イギリス", .amount.count = 144, COUNT};
FruitOrder strawberries = {"いちご", "スペイン", .amount.weight = 17.6,
POUNDS};
FruitOrder oj = {"オレンジジュース", "アメリカ", .amount.volume = 10.5,
PINTS};
display(apples);
display(strawberries);
display(oj);
}
入出力結果(Terminal)
$ make cc sample.c -o sample ./sample この注文に含まれるものは144個の林檎です この注文に含まれるものは17.60ポンドのいちごです この注文に含まれるものは10.50パイントのオレンジジュースです $
0 コメント:
コメントを投稿