Top
プログラム課題集
HIT & BLOW改解答例
#include
"
stdafx.h
"
#include
"
time.h
"
#include
"
stdlib.h
""
#include
"
stdio.h
"
int main()
{
srand((unsigned int)time(NULL));
FILE* fp = NULL;
int resultCount = 0;
int gameCount = 0;
// データ読込
fopen_s(&fp,
"data.txt"
,
"r"
);
if (fp != NULL)
{
fscanf_s(fp,
"%d"
, &resultCount);
fclose(fp);
printf(
"あなたのクリアまでの最小トライ回数は%dです。\n"
, resultCount);
}
else
{
resultCount = -1;
printf(
"あなたはまだクリアしたことがありません。\n"
);
}
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);
gameCount++;
} while (hits < 3);
printf(
"あなたのクリア回数は%dです\n"
, gameCount);
if ( (resultCount > gameCount) || (resultCount == -1))
{
// データ書き込み
fopen_s(&fp,
"data.txt"
,
"w"
);
fprintf_s(fp,
"%d"
, gameCount);
fclose(fp);
}
return 0;
}