書籍
- C言語プログラミング ハーベイ M.ダイテル (著), ポール J.ダイテル (著), 小嶋 隆一 (翻訳)
- 開発環境
- Visual Stdio Code
- gcc 8.1.0
10.7: リスト10.9(P.388)のプログラムを利用して、(リスト10.2(P.374)に示した)高性能なカード混合・分配シミュレーションを行うプログラムを作成
C言語
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
// カード構造体
typedef struct bitCard{
unsigned face : 4;
unsigned suit : 2;
unsigned color : 1;
}Card;
void fillDeck(Card *);
void shuffle(Card *);
void deal(Card *, char *[], char *[], char *[]);
int main()
{
Card deck[52];
char *face[] = {"エース", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"ジャック", "クィーン", "キング"};
char *suit[] = {"ハート", "ダイヤ", "クラブ", "スペード"};
char *color[] = {"赤", "黒"};
// srand(time(NULL));
fillDeck(deck);
shuffle(deck);
deal(deck, face, suit, color);
getch();
return 0;
}
void fillDeck(Card *wDeck)
{
int i;
for (i = 0; i <=51; i++)
{
wDeck[i].face = i % 13;
wDeck[i].suit = i / 13;
wDeck[i].color = i / 26;
}
}
void shuffle(Card *wDeck)
{
int i, j;
Card tmp;
for (i = 0; i <= 51; i++)
{
j = rand() % 52;
tmp = wDeck[i];
wDeck[i] = wDeck[j];
wDeck[j] = tmp;
}
}
void deal(Card *wDeck, char *wFace[], char *wSuit[], char *wColor[])
{
int k1;
//int k2;
/*
for (k1 = 0, k2 = k1 + 26; k1 <= 25; k1++, k2++)
{
printf("%10s : %8s の %-8s\t",
wColor[wDeck[k1].color], wSuit[wDeck[k1].suit], wFace[wDeck[k1].face]);
printf("%10s : %8s の %-8s\n",
wColor[wDeck[k2].color], wSuit[wDeck[k2].suit], wFace[wDeck[k2].face]);
}
*/
for (k1 = 0; k1 <= 51; k1++)
{
printf("%6s : %8s の %-8s%c",
wColor[wDeck[k1].color], wSuit[wDeck[k1].suit], wFace[wDeck[k1].face], (k1 + 1) % 2 ? '\t' : '\n');
}
}
10.8: char c, short s, int i, long lをメンバとする共用体integerを作り値を格納、かつ、中身を表示するプログラム
C言語
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
typedef union integer{
char c;
short s;
int i;
long l;
}Integer;
int main()
{
Integer a;
Integer b;
Integer c;
Integer d;
a.c = 'a';
printf("1\n");
printf("%c\n", a.c);
printf("%d\n", a.i);
printf("%ld\n", a.l);
printf("%hd\n", a.s);
b.s = (short)10;
printf("2\n");
printf("%c\n", b.c);
printf("%d\n", b.i);
printf("%ld\n", b.l);
printf("%hd\n", b.s);
c.i = 19;
printf("3\n");
printf("%c\n", c.c);
printf("%d\n", c.i);
printf("%ld\n", c.l);
printf("%hd\n", c.s);
d.l = (long)1000;
printf("4\n");
printf("%c\n", d.c);
printf("%d\n", d.i);
printf("%ld\n", d.l);
printf("%hd\n", d.s);
getch();
return 0;
}
10.9: float f, double d, long double lをメンバとする共用体floatingPointを作り値を格納、かつ、中身を表示するプログラム
C言語
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <signal.h>
typedef union floatingPoint{
float f;
double d;
long double l;
}FloatingPoint;
int main()
{
FloatingPoint a;
FloatingPoint b;
FloatingPoint c;
a.f = 4.0f;
b.d = 5.0;
c.l = 5.1L;
printf("a\n");
printf("%f\n", a.f);
printf("%lf\n", a.d);
printf("%Lf\n", a.l);
printf("\nb\n");
printf("%f\n", b.f);
printf("%lf\n", b.d);
printf("%Lf\n", b.l);
printf("\nc\n");
printf("%f\n", c.f);
printf("%lf\n", c.d);
printf("%Lf\n", c.l);
getch();
return 0;
}
reference
- a
- b
10.:
C言語
