Reliable guessing game

Today to introduce a fun little game - guessing, many people have played this game, but that is where I hope you enjoy the joy of the game but also understand the nature of this game.
First let us look at the design selection interface of the game:

void menu()
{
	printf("***************************\n");
	printf("****  1.play   0.exit  ****\n");
	printf("***************************\n");
}

Of course, we can according to their own preferences to put it to become a diversified, providing a model where
the second part we want to ensure selection interface can go smoothly:

int input = 0;
do
	{
		menu();
		printf("请选择:<\n");
		scanf("%d",&input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			break;
		default:
			printf("选择错误,请重新选择\n");
			break;
		}
	} while (input);

Here used do while statement, it can guarantee in case you do not want to quit can continue to select
the next and most critical step: we need to design this game.

void game()
{
	int guess = 0;
	int ret = rand() % 100 + 1;
	while (1)
	{
		printf("请输入要猜的数字<:");
		scanf("%d",&guess);
		if (guess > ret)
		{
			printf("猜大了\n");
		}
		else if (guess < ret)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("恭喜你,猜对了!\n");
			break;
		}
	}
}

This is a cycle can always guess the number of statements when you guess is compared with the given random number can prompt you guessing range.
That's all our guessing game anyway.
Next, we will introduce some of the details of the code here:

rand function, its role is the computer returns a random integer between 1-RAND_MAX, i.e. 1-32767.

Specific applications are as follows: v2 = rand() % 100 + 1; // v2 in the range 1 to 100
This is to determine the scope of his to help us guess.

srand function is provided a random number generator before calling rand

General and srand function with time function is used, the time function of the type of cast unsigned int, an action which is to return a time stamp, i.e. a computer function call time of the start time and said computer (1970.1. 10: 0: 0 is a difference between), in seconds
application method: srand((unsigned)time(NULL));
and srand function can only be called once, do not call frequently, otherwise the resulting number is not random.
Call time function header file #include <time.h>
call srand, rand function to the header file #include <stdlib.h>

Released five original articles · won praise 0 · Views 118

Guess you like

Origin blog.csdn.net/Noreturnperiod/article/details/105058933