Top プログラム課題集


HIT & BLOW解答例
下記が解答例になります。
見てもらえれば分かりますが、最低限仕様を満たすためのソースコードになっており、
模範的な解答ではありません。
・配列を使ってないから無駄にコードが長くなっている。
・数字以外の文字を入力されたら誤作動する
・数字の範囲チェックを行っていない
等々課題は沢山あります。
どうやればよりよくなるか、考えてみて下さい。

#include "stdafx.h"
#include "time.h"
#include "stdlib.h""

int main()
{
srand((unsigned int)time(NULL));

int count = 0;
int box1 = 0;
int box2 = 0;
int box3 = 0;
// 準備
while(count < 3)
{
switch (count)
{
case 0:
box1 = rand() % 9 + 1;
count++;
break;
case 1:
box2 = rand() % 9 + 1;
if (box1 != box2)
{
count++;
}
break;
case 2:
box3 = rand() % 9 + 1;
if ((box1 != box3) && (box2 != box3))
{
count++;
}
break;
}
}

int hits = 0;
int blows = 0;
int input1 = 0;
int input2 = 0;
int input3 = 0;
do
{
hits = 0;
blows = 0;
printf("スペース区切りで1~9の3個の数字を入力してください\n");
scanf_s("%d", &input1);
scanf_s("%d", &input2);
scanf_s("%d", &input3);

// Hit判定
if (input1 == box1)
{
hits++;
}
if (input2 == box2)
{
hits++;
}
if (input3 == box3)
{
hits++;
}

// Blow判定
if (input1 == box2)
{
blows++;
}
if (input1 == box3)
{
blows++;
}
if (input2 == box1)
{
blows++;
}
if (input2 == box3)
{
blows++;
}
if (input3 == box2)
{
blows++;
}
if (input3 == box1)
{
blows++;
}
printf("hit:%d blow:%d\n",hits,blows);
} while (hits < 3);

return 0;
}