Head First C ―頭とからだで覚えるCの基本
(オライリージャパン)
David Griffiths (著) Dawn Griffiths (著)
中田 秀基(監訳)(翻訳) 木下 哲也 (翻訳)
開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang (コンパイラ)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の5章(構造体、共用体、ビットフィールド)、コードマグネット(p.256)を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
- C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、 谷口 功 (翻訳)、 オライリージャパン)
コードマグネット(p.256)
コード(BBEdit, Emacs)
sample256.c
#include <stdio.h>
typedef enum {
COUNT, POUNDS, PINTS
} unit_of_measure;
typedef union {
short count;
float weight;
float volume;
} quanntity;
typedef struct {
const char *name;
const char *country;
quanntity amount;
unit_of_measure units;
} fruit_order;
void display(fruit_order 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("%d個の%sです。\n", order.amount.count, order.name);
}
}
int main(int argc, char *argv[])
{
fruit_order apples = {"リンゴ", "イギリス", .amount.count=144, COUNT};
fruit_order strawberries = {"いちご", "スペイン", .amount.weight=17.6,
POUNDS};
fruit_order oj = {"オレンジジュース", "アメリカ", .amount.volume=10.5,
PINTS};
int n = 3;
fruit_order fruit_orders[3] = {apples, strawberries, oj};
int i;
for (i = 0; i < n; i++) {
display(fruit_orders[i]);
}
return (0);
}
Makefile
sample256: sample256.c cc -g -o sample256 sample256.c clean: rm sample256
入出力結果(Terminal)
$ make && ./sample256 cc -g -o sample256 sample256.c この注文に含まれるものは144個のリンゴです。 この注文に含まれるものは17.60ポンドのいちごです。 この注文に含まれるものは10.50パイントのオレンジジュースです。 $
0 コメント:
コメントを投稿