很喜欢C Primer Plus的一句话:用好循环与指针相当于拥有了C语言中的倚天剑与屠龙刀。
因此,学好循环很重要。
以下是猜数(终极版)游戏的代码
(编译器为vs2022)
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
int main(void)
{
int magic, guess, ret;
int counter = 0;
char reply;
srand(time(NULL));
do {
magic = rand() % 100 + 1;
counter = 0;
do {
printf("Please guess a magic number: ");
ret = scanf("%d", &guess);
while (ret != 1)
{
while (getchar() != '\n');
printf("Please guess a magic number:");
ret = scanf("%d", &guess);
}
counter++;
if (guess > magic)
{
printf("Wrong! Too big!\n");
}
else if (guess < magic)
{
printf("Wrong!Too small\n!");
}
else
printf("答对了,我的老baby\n");
} while (guess != magic && counter < 10);
printf("counter = %d\n", counter);
printf("Do you want guess again?(Y/N or y/n)?");
scanf(" %c", &reply);
} while (reply == 'Y' || reply == 'y');
return 0;
}