任务描述
本关任务:猜数游戏。
相关知识
为了完成本关任务,你需要掌握:C 语言基础。
猜数游戏
在上一关的基础上继续编写此次游戏。编程先由计算机“想”一个1~100
之间的数请玩家猜,如果玩家猜对了,在屏幕上输出玩家猜了多少次才猜对此数,以此来反映玩家“猜”数的水平,则结束游戏;否则计算机给出提示,告诉玩家所猜的数是太大还是太小,最多可以猜10
次,如果猜了10
次仍未猜中,则停止本次猜数,然后继续猜下一个数。每次运行程序可以反复猜多个数,直到玩家想停止时才结束。
测试输入:
50
13
10
24
预期输出:
Please guess a magic number:50
Wrong!Too high!
Please guess a magic number:13
Wrong!Too low!
Please guess a magic number:10
Wrong!Too low!
Please guess a magic number:24
Right!
The number is:24
counter=4
Do you want to continue(Y/N or y/n)?
答案:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int magic; //计算机"想"的数
int guess; //玩家猜的数
int counter; //记录玩家猜的次数
char reply; //玩家输入的回答
srand(11);
/*************** Begin ***************/
do{
magic = rand() % 100 + 1;
counter = 0;
do{
printf("Please guess a magic number:");
scanf("%d", &guess);
counter ++;
if (guess > magic)
{
printf("Wrong!Too high!\n");
}
else if (guess < magic)
{
printf("Wrong!Too low!\n");
}
else
{
printf("Right!\n");
}
}while (guess!=magic && counter<10);//猜错且未超10次时继续猜
printf("counter = %d\n", counter);
printf("Do you want to continue(Y/N or y/n)?");
scanf(" %c", &reply); // %c前面有一个空格
}while ((reply == 'Y') || (reply == 'y'));
/*************** End ***************/
printf("The game is over!\n");
return 0;
}