Complete the guessing number game (simple application of random number generation function and binary search algorithm ideas).

Regarding this kind of game, we write it in modules. For this number guessing game, we divide it into three modules, the game menu module, the game main module, and the main function module.

The game menu module does not need to be explained in detail. It is very simple.
In C language, we generally use the rand() function in the <stdlib.h> header file to generate random numbers. Its usage is:

int rand (void);   

void means no parameters need to be passed.
There is also a random() function in the C language that can obtain random numbers, but random() is not a standard function and cannot be passed by compilers such as VC/VS, so it is rarely used.
rand() will randomly generate an integer between 0 ~ RAND_MAX.

RAND_MAX is a macro in the <stdlib.h> header file, which is used to specify the maximum random number that rand() can return. The C language standard does not specify the specific value of RAND_MAX, but only stipulates that its value is at least 32767. In actual programming, we don't need to know the specific value of RAND_MAX, we can just treat it as a large number.
The following is an example of random number generation

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a = rand();
    printf("%d\n",a);
    return 0;
}

The nature of random numbers

Run the above code multiple times, and you will find that the random numbers generated are the same every time. What is going on? Why are random numbers not random?

In fact, the random numbers generated by the rand() function are pseudo-random numbers, which are calculated according to a certain formula based on a numerical value. This numerical value is called a "seed". The relationship between seeds and random numbers is a normal distribution, as shown in the figure below:
Insert image description here

The seed is random every time the computer is started, but it does not change once the computer is started; that is to say, the seed is a fixed value every time the computer is started, so the result calculated according to the formula (that is, the generated random number) is fixed.

Redefine seeds

We can re-seed through the srand() function, so that the seed will change. The usage of srand() is:

void srand (unsigned int seed);

It requires a parameter of type unsigned int. In actual development, we can use time as a parameter. As long as the sowing time is different each time, the generated seeds will be different, and the final random numbers will also be different.

Use the time() function in the <time.h> header file to get the current time (accurate to seconds), as follows:

srand((unsigned)time(NULL));

Modify the above code to seed before generating random numbers:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    int a;
    srand((unsigned)time(NULL));
    a = rand();
    printf("%d\n", a);
    return 0;
}

If you run the program multiple times, you will find that the random numbers generated are different each time. However, these random numbers will have a tendency to gradually increase or decrease. This is because we use time as the seed, and time gradually increases. Combined with the normal distribution diagram above, it is easy to infer that the random numbers will also gradually increase. increase or decrease.

Generate random numbers within a certain range

In actual operation, we need random numbers within a certain range. If they are too large or too small, we will use the modulo method to generate random numbers within a certain range: the method is as follows

int a = rand() % 10;    //产生0~9的随机数

If you want to specify upper and lower limits:

int a = rand() % 100 + 1;    //产生1~100的随机数

Analysis: Taking the modulo means taking the remainder. We can think of rand()%100+1 as two parts: rand()%100 generates random numbers from 0 to 99, and the following +1 ensures that the minimum a can only be 1, and the maximum is 99. +1=100. code show as below

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
    int a;
    srand((unsigned)time(NULL));
    a = rand() % 100+ 1;
    printf("%d\n",a);
    return 0;
}

Compare the input number with the number generated by the random function

The idea of ​​binary search is to compare the input number with the number generated by the random function. If it is larger, continue to guess backward and take half of the value in the subsequent interval. If it is smaller, continue to guess forward and take half of the previous interval. Just that value

The complete code is as follows

#include<stdio.h>
#include <stdlib.h>
#include <time.h>
//游戏菜单模块
int meun() {
    printf("*********************\n");
    printf("欢迎来到猜数字游戏!\n");
    printf("1.开始游戏\n");
    printf("0.结束游戏\n");
    printf("*********************\n");
    printf("请输入你的选择:");
    int choice = 0;
    scanf("%d", &choice);
    return choice;
}
//游戏主模块
int Game() {
    int b = 0;
    srand((unsigned) time(NULL));
    int toGuess = rand() % 101;
    while (1) {
        printf("请输入要猜测的数字(0-100)\n");
        scanf("%d", &b);
        if (b == toGuess) {
            printf("你猜对了");
            break;
        } else if (b > toGuess) {
            printf("你猜大了!");
        } else {
            printf("你猜小了");
        }
    }
}
//主函数
int main(void) {
    while (1) {
        int choice = meun();
        if (choice == 1)
            //开始游戏
            Game();
        else if (choice == 0) {
            printf("Good Bye!\n");
            break;
        } else {
            printf("您输入有误!\n");
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_42440457/article/details/103165762