Author Xie Enming, public number “programmer union”. Please indicate the source of reprint. Original: www.jianshu.com/p/7d03f054c…

The whole series of C language Exploration

Content abstract


  1. preface
  2. Preparation and suggestions
  3. My code
  4. The improved scheme
  5. Part 1 Lesson 11 Notice

1. Introduction


A lesson is the first part of the C language to explore trip | lesson 9: loop statement.

After so many lessons, we finally ushered in the first relatively formal program: a C language game.

The game doesn’t have a graphical interface, it’s a command line, but it’s a small milestone nonetheless.

Our goal is to show you that after the last few lectures, you can do something interesting.

Although we know that theory is good, it is meaningless if we can’t put what we have learned into practice.

Believe it or not, you actually have the ability to implement your first interesting program.

2. Preparation and suggestions


Principle of program

Before I start programming, I have to tell you what this program does.

We can call this game More or less.

Here’s how the game works:

  1. For each round the computer randomly draws an integer from 1 to 100.

  2. The computer asks you to guess the number, so you enter an integer between 1 and 100.

  3. The computer compares the number you enter with the number it draws and tells you whether your number is higher or lower than its number.

  4. It then asks you to enter the numbers again and tells you the result of the comparison.

  5. Until you guess that number, one round is over.

The object of the game, of course, is to guess the “mystery” number as few times as possible. It doesn’t have a fancy graphical interface, but more or less, this is your first game and you should be proud of it.

Here is an example of the style of the round that you will program to implement:

What is this number? 50 guess too small! What is this number? 75 guess small! What is this number? 85 big guess! What is this number? 80 big guesses! What is this number? 78 guess small! What is this number? 79 amazing, you guessed the mystery number!!Copy the code

Pick a random number


But the question is, “How do you pick a number at random? I don’t know what to do. I can’t do it.”

Of course, we haven’t learned how to generate a random number yet. It’s not easy to ask dear computer to do this: it’s good at arithmetic, but it doesn’t know how to pick a random number.

In fact, in order to “try” to get a random number, we have to ask a computer to do some complicated calculations. Well, it comes down to doing calculations.

We have two solutions:

  • Ask the user to enter this mysterious number through scanf, and then you need two players. One picks a number, one guesses a number.

  • It’s a gamble that the computer will automatically generate a random number for us. The upside: you only need one player to entertain yourself. Downside: need to learn what to do…

We’ll learn how to write the game in the second way, but you can also code the first way later.

To generate a random number, we use the rand() function.

As the name implies, this function generates random numbers for us. But we also want the random number to be in the integer range from 1 to 100 (which would be complicated if there were no bounds).

We will use the following form:

srand(time(NULL));
mysteryNumber = (rand() % (MAX - MIN + 1)) + MIN;
Copy the code

The first line (the srand function) initializes the generator for random numbers. Srand is actually an abbreviation of seed Random. Seed means “seed” in English.

Give a simple explanation of Baidu Baike:

Srand and RAND are used together to produce a sequence of pseudorandom numbers. Before generating random numbers, the RAND function needs a seed provided by the system to generate a sequence of pseudo-random numbers. Rand generates a series of random numbers based on the value of this seed. If the seed supplied by the system does not change, the sequence of pseudorandom numbers generated by each call to the RAND function is the same. Srand (unsigned seed) uses the seed parameter to change the seed value provided by the system, which can make the sequence of pseudo-random numbers generated by each call to the RAND function different, thus realizing “randomness” in the true sense. It is usually possible to use the system time to change the seed value of the system, namely SRand (time(NULL)), which can provide a different seed value for the RAND function to generate different random number sequences.


The so-called “pseudo-random number” is not a fake random number, here “pseudo-” means regular. In fact, absolute random number is only an ideal random number, the computer can only generate relative random number that is pseudo-random number. Computer-generated pseudo-random numbers are both random and regular — some follow certain rules and some follow none. For example, “No two leaves in the world are exactly the same shape”, which points to the nature of things — regularity; But the leaves of every tree have a similar shape, and this is the commonness of things — the regularity. From this perspective, we can accept the fact that computers can only generate pseudo-random numbers, not absolute random numbers.


The current Calendar time of the computer system can be obtained through the time() function. The functions dealing with date and time are based on the return value of this function. The prototype is: time_t time(time_t * t); If you have declared the parameter t, you can return the current calendar time from the parameter T, as well as the number of seconds from a point in time (for example, 00:00 00:00 on January 1, 1970) to the present time by returning a value. If the argument is NULL, the function returns the current calendar time only by returning the value.

If we did not specify the seed before using the rand function, or if we did use srand but gave it a constant argument, such as srand(1), the number would be the same every time the program ran RAND. Only by giving a seed value that is different each time, such as the time() function, can rand return a different value and be “random”.

The srand function needs to be called only once before the rand function. After that, you can call the RAND function as many times as you want, but you can’t use srand twice in each program.

MAX and MIN in the above code format are constants or const variables. MAX is an abbreviation of Maximum. MIN is the abbreviation for Minimum. As the name implies, MAX and MIN are the maximum and minimum values of the range you specify, respectively.

It is recommended to define these two const variables at the beginning of the program:

const int MAX = 100, MIN = 1;
Copy the code

Introduced in the library


In order for the program to run smoothly, we need to introduce three libraries:

  • stdio.h
  • stdlib.h
  • time.h

We talked about libraries in previous lectures. The library provides some defined functions, such as our time() function in time.h and the rand and srand functions in stdlib.

Okay, I’m not going to go any further. We’ve explained how the game works, given an example of how to run a round of the game, and given the main random number generation code. It’s your turn to complete the game code. Come on, I believe you can do it!

My code


I want you to start by writing code, looking up some materials, or reviewing what we’ve done in the last few lectures. See if it works or if you can’t write it.

My version is given below. Of course, there are different versions of the game code. You can do it on your own.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>int main (int argc, char** argv) { int mysteryNumber = 0, guessNumber = 0; const int MAX = 100, MIN = 1; // Generate random number srand(time(NULL)); mysteryNumber = (rand() % (MAX - MIN + 1)) + MIN; /* The loop part of the program, if the user did not guess the number, the loop continues */do{// Ask the user to enter the guessed numberprintf("What is this number? ");
        scanf("%d", &guessNumber); // Compare the number entered by the user with the mysterious numberif (mysteryNumber > guessNumber)
            printf("Small guess! \n\n");
        else if (mysteryNumber < guessNumber)
            printf("Big guess! \n\n");
        else
            printf ("Great, you guessed the mystery number!! \n\n");
    } while(guessNumber ! = mysteryNumber);return 0;
}
Copy the code

Explanation of the program (from top to bottom) :

  1. Preprocessing instruction: the first three lines, starting with #. Include, include, include, include

  2. Variables: In this game, there are not many variables, just a variable guessNumber for recording the number entered by the user and a random number chosen by the computer. A. guess B. mystery C. number D. mystery We also define two constants MAX and MIN with values of 100 and 1, respectively. The nice thing about this definition is, if you want to change these two values later, it’s very convenient, just change the two values in this row. If you write 100 and 1 everywhere in the program instead of MAX and MIN, it will be too much work to change values later.

  3. Random number: The srand and RAND lines are used to generate a random number between 1 and 100 that is assigned to mysteryNumber.

  4. Loop: I choose do… The while loop. Theoretically a while loop could do it, but I think we’re using do here… While might be more logical. Why is that? Do you remember the do… While loop? That is, the instruction in the body of the loop will be executed at least once, unlike the while loop which may not be executed at all. Here we want the user to enter the number at least once, it’s impossible for the user to guess the number without entering it once.

  5. On each run into the body of the loop, we ask the user for a number, assign the value to the guessNumber variable, and then compare the guessNumber and mysteryNumber:

    • MysteryNumber is larger than guessNumber, then the output is “guess small” and the loop continues;
    • MysteryNumber is smaller than guessNumber, then the output is “guess big” and the loop continues.
    • MysteryNumber equals guessNumber, which is the else statement, indicating that we are right, and the output is “great, you guessed the mysteryNumber!” , end the loop.
  6. The loop also needs a condition, which we give: as long as the guess number is different from the mystery number, the loop continues.

4. Improvement plan

At present, the game is very basic and simple, but there can be the following improvements:

  1. Add a counter that tracks steps, and when you get it right: “Great, you guessed the mystery number with ** steps!”

  2. The current program ends after one round, but what if the player doesn’t enjoy it and wants to go on to the next round? Add a question: “Do you still want to play?” Wait for the user to enter a number to answer. Define a Boolean value continue (continue means “continue”) to store the user’s input. For example, the default value of continue is 1, which means that the user defaults to continue to the next round. But if the user enters 0, the program stops and the game ends.

  3. Added a mode: two-player mode. You can write the questions and I’ll guess. But I want you to let the user choose which mode to play at the beginning of the application, classic man-machine versus man-player. Instead of using SRand and RAND to generate a mysterious number in a two-player game, players can enter the number using scanf.

  4. Set several difficulty levels and let the player choose from: elementary (a number from 1-100), Intermediate (a number from 1-1000), and advanced (a number from 1-10000). If you do this, you need to rewrite MAX, and MAX can no longer be a const. You have to drop the const before MAX and keep the MIN.

You can also add your own difficulty and come up with more fun ideas to enrich the game. You’ll learn more by refining and improving this little game.

5. Part 1 Lesson 11 Notice


That’s all for today’s lesson, come on!

The next lesson: the first part of C language to explore trip | lesson 9: function

In the next lesson, let’s learn about functions, which are extremely important and useful.


I am Xie Enming, the operator of the public account “Programmer Union”, and the moOCs elite lecturer Oscar, a lifelong learner. Love life, like swimming, a little cooking. Life motto: “Run straight for the pole”