C language game (1) ---- guessing game

content

foreword

Judgment of the number of madness

if else statement

Repeat until you guess correctly (do statement, while statement)

Randomly set target numbers

The srand function shows great power

Limit the number of times and save input records

end


foreword

Shi Lu.C language mini game series is expected to have a total of 10 , which is more suitable for programmers who have already learned the introductory content of C language and want to master the actual programming ability.

Guessing games should be available in everyone's textbooks for beginners. The difficulty factor is not large , and it belongs to the kind of program that is passed through once. But even the smallest flies have meat! In fact, the guessing game also contains many practical skills . Long story short, let's listen to Shi Lu. Explain the C language game for you who are eager to improve (1) - guessing game .

Judgment of the number of madness

Let's start with a beta version of the "guessing game". Compare the value typed with the "target number" through the if else statement, scanf function, and display the result of the comparison.

#include <stdio.h>

int main()
{
	int no;
	int ans = 5;

	printf("Please guess0--9:\n");

	printf("是多少呢?\n");
	scanf("%d", &no);

	if (no > ans)
		printf("Too big!\n");
	else if (no < ans)
		printf("Too small\n");
	else
		printf("Yes!You are right!\n");     \\    \n是一种转义字符,表示换行

	return 0;
}

The number established in this game is 5. If the input number is less than 5, output Too small! ; if the input number is greater than 5, output Too big! .

if else statement

The if statement in this program takes the following form.

if (expression) statement else if (expression) statement else statement

There can be many else ifs , depending on the number of conditions the programmer wants to design.

Next, we discuss the method of multi-branching, that is, use the above statement to compare the other two if else morphological statements to obtain the advantages and disadvantages. Without further ado, let's get to the code!

if(no > ans)
    printf("Too big!\n");
else if(no < ans)
    printf("Too small!\n");
else
    printf("Yes!You are right!\n");          //1



if(no > ans)
    printf("Too big!\n");
else if (no < ans)
    printf("Too small!\n");
else if (no == ans)
    printf("Yes!You are right!\n");          //2



if(no > ans)
    printf("Too big!\n");
if (no < ans)
    printf("Too small!\n");
if (no = ans)
    printf("Yes!You are right!\n");          //3

Let's analyze programs 2 and 3 compared to 1 to see what conclusions can be drawn. Program 2 adds (no==ans) judgment to program 1, which is actually very redundant ; the three ifs of program 3 are juxtaposed, regardless of the size relationship between no and ans, the program will judge these three conditions .

Next, we analyze the judgments made by programs 1, 2, and 3 through the chart to see what conclusions can be drawn. The following [1] judges no>ans, [2] judges no<ans, and [3] judges no==ans.

size relationship no>ans when no<ans when no==ans
1 【1】 【1】【2】 【1】【2】
2 【1】 【1】【2】 【1】【2】【3】
3 【1】【2】【3】 【1】【2】【3】 【1】【2】【3】

From the above, it can be concluded that the efficiency of program 1 is the highest .

Repeat until you guess correctly (do statement, while statement)

The previous program that only allowed the player to enter a value once was very boring. So we improved the program so that the player could keep repeating until they guessed correctly . So how do we implement input multiple times? It's time for the loops we learned to come in handy. Use the do statement loop to achieve multiple input , the code is as follows:

#include <stdio.h>

int main()
{
	int no;
	int ans = 7;

	printf("请猜一个0-9的数。\n\n");

	do {
		printf("是多少呢?\n");
		scanf("%d", &no);

		if (no > ans)
			printf("Too big!\n");
		else if (no < ans)
			printf("Too small!\n");
		else
			printf("Yes!You are right!\n");
	} while (no != ans);

	return 0;
}

The do statement is looped first and then judged , which is different from its good brothers, the while statement and the for statement (which will be discussed later). In the process of applying the do statement, always remember that there is a semicolon ";" at the end of it. As shown above, the controlling expression of the do statement is no!=ans, operator! = evaluates the condition that the values ​​of the left and right operands are not equal. If this condition is true, the program will generate an int type 1 to indicate continuation, and if not, generate an int type 0 to indicate the end of the loop.

Next, let's take a look at using the while statement to implement the guessing game:

#include <stdio.h>

int main()
{
	int no;
	int ans = 7;

	printf("请猜一个0-9的数。\n\n");

	while (1) {
		printf("是多少呢?\n");
		scanf("%d", &no);

		if (no > ans)
			printf("Too big!\n");
		else if (no < ans)
			printf("Too small!\n");
		else
			break;
	}
	printf("Yes!You are right!\n");
	
	return 0;
}

The while statement is to judge first and then loop , which is different from the looping method of the previous do statement. As above, the control expression of while is 1, so the loop will go on forever. Isn't such a loop an "infinite loop"? How to break this cycle? The break statement is very powerful, directly forcing out of the loop statement.

Randomly set target numbers

In the previous game, guessing the numbers you set by yourself was too boring. If you can randomly generate numbers to guess, it will add a lot of fun. Thinking about it, it seems that we can use the rand function to generate random numbers. The function of rand is to calculate 0-RAND_MAX ( many beginners do not know RAND_MAX, this is actually a macro contained in the header file <stdlib.h>, which stipulates that its value cannot be less than the minimum number specified by the compilation environment, and the minimum is 32767 ) of pseudorandom integer sequences. What is "pseudo"? Let me analyze one by one. Code first:

#include <stdio.h>
#include <stdlib.h>        

int main()
{
	int retry;          //再运行一次?

	printf("在这个编译环境中能够生成0-%d的随机数。\n", RAND_MAX);

	do {
		printf("\n生成了随机数%d。\n", rand());

		printf("再运行一次?  (0)否(1)是:");
		scanf("%d", &retry);
	} while (retry == 1);

	return 0;
}

Smart friends can check the compiler by ctrl+c. After executing the program several times, you will find that the generated random sequence is exactly the same! The rand function seems to be random, but it is not random, and there are certain rules to follow. why? This is because the default seed for the rand function (the rand function operates on a reference value called a "seed" to generate random numbers) is 1. If we want to generate a different random sequence, we have to change the value of the seed.

The srand function shows great power

The srand function can solve the dilemma described above. Its function is to set a seed for subsequent calls to the rand function to generate a new sequence of pseudorandom numbers. If this function is called with the same seed value, the same sequence of pseudo-random numbers will be generated. If the rand function is called before calling this function, it is equivalent to calling this function at the beginning of the program, setting the seed to 1, and finally generating a sequence with a seed value of 1. In addition, other library functions will ignore the call of this function at runtime.

How to express it? For example, srand(50) and srand(40), the random sequences they generate are different, and see the following table:

When the seed is 50, it generates 235->666->777->231->3489.....
When the seed is 40, it generates 222->2678->2235->1463->87.....

Next, if we want to change the seed from a constant to a random value, we can refer to the time() of the header file <time.h>, by using the time when the program is run as the seed. Above code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
	int retry;

	srand(time(NULL));

	printf("在这个编译环境中能够生成0-%d的随机数。\n", RAND_MAX);

	do {
		printf("\n生成了随机数%d。\n", rand());

		printf("再运行一次?  (0)否(1)是:");
		scanf("%d", &retry);
	} while (retry == 1);

	return 0;
}

RAND_MAX mentioned above that the number it generates may be very large, possibly tens of thousands or hundreds of thousands. So how do we control the random values ​​generated by srand? We can use the remainder operation to achieve this. Popularize the concept of surplus . please look below:

rand()%6 is a random number from 0 to 5, because the result of the remainder operation will not be greater than the remainder

, Let's modify the above code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
	int retry;

	srand(time(NULL));

	printf("在这个编译环境中能够生成0-%d的随机数。\n", RAND_MAX);

	do {
		printf("\n生成了随机数%d。\n", rand());

		printf("再运行一次?  (0)否(1)是:");
		scanf("%d", &retry);
	} while (retry == 1);

	return 0;
}

This way the game won't be boring anymore! But there seems to be a lack of excitement , and we should upgrade the program again - limit the number of times and save the input record .

Limit the number of times and save input records

If the game can limit the number of player input and save the value input by the player, the player's gaming experience will definitely be greatly upgraded! When we think of saving input values, we can definitely think of saving them in arrays . Through array traversal , the values ​​entered by the player are stored one by one, and presented to the player after the game is over, so that the player knows how close the number he guessed is to the target number. Code first:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_STAGE 10

int main()
{
	int i;
	int stage;           //玩家已经操作的次数
	int no;
	int ans;
	int num[MAX_STAGE];        //玩家能操作的最大次数

	srand(time(NULL));
	ans = rand() % 1000;

	printf("请猜一个0-999的整数。\n\n");

	stage = 0;
	do {
		printf("还剩%d次机会。是多少呢: ", MAX_STAGE - stage);
		scanf("%d", &no);
		num[stage++] = no;

		if (no > ans)
			printf("Too big!\n");
		else if (no < ans)
			printf("Too small!\n");
	} while (no != ans && stage < MAX_STAGE);

	if (no != ans)
		printf("很遗憾,正确答案是%d。\n", ans);
	else
	{
		printf("Yes!You are right!\n");
		printf("您用了%d次猜中了。\n", stage);
	}

	puts("\n--- 输入记录 ---");
	for (i = 0; i < stage; i++)
		printf(" %2d:%4d %+4d\n", i + 1, num[i], num[i] - ans);

	return 0;
}

Let's analyze the code above.

(1) Let's start with a wrong example. Junior programmers often make the following mistakes :

int n=10;
int arr[n]={0};

At first glance it looks similar to the above, but in fact this is a wrong way of writing. It is the correct way to define a macro first, and then refer to the macro in the array [] ;

(2) The code num[stage++]=no; is a postfix ++ , which uses a for loop to increase the number of stages. Through repeated loop processing, the values ​​input by the player can be stored in the array in sequence.

(3) In this code, we use the for statement not mentioned above to display the output records . Let's pull this code out and explain it separately:

for (i = 0; i < stage; i++)
		printf(" %2d:%4d %+4d\n", i + 1, num[i], num[i] - ans);

First, set the value of i to 0. When the value of i is less than stage, it will continue to increase the value of i by +1, so as to let the loop body run the stage times (the value of stage is equal to the number of times the player enters the value).

%2d %4d The number before the symbol and the letter represents their field width, and the +4 in %+4d aligns the number to the right.

The following · represents a space, take 125 as an example
%4d     125·
%+4d    ·125

end

The above is Shi Lu. The understanding and analysis of the first game in this series, the word guessing game, thank you for watching here! If you think this blog is helpful to you who are learning programming, please give Shi Lu. more support and attention! In the next 10 days or so, Shi Lu. will play other games implemented by programming with you. I hope I can offer you better games next time, and I hope that the next blog will have you!


 

Guess you like

Origin blog.csdn.net/qq_64263760/article/details/122880908