Experiment 4-1-9 Number Guessing Game (15 points)

The number guessing game is to make the game machine randomly generate a 100positive integer within a number. The user enters a number to guess it. You need to write a program to automatically compare it with the randomly generated guessed number, and prompt whether it is bigger (“Too big”)or smaller (“Too small”). Equality means guessed. If it is guessed, the program ends. The program also requires counting the number of guesses Bingo!. If 3the number is guessed once, it prompts " Lucky You!"; if the number is guessed within a time, it prompts" "; if the number is guessed more than 3once but within the N(>3)time (including the first Ntime), It will prompt " Good Guess!"; if you Nhaven't guessed it more than once, it will prompt" Game Over"and end the program. If the Nuser inputs a negative number before reaching the second time, " Game Over" is also output and the program ends.

Input format:

Enter two 100positive integers that do not exceed in the first line , which are the random number generated by the game machine and the maximum number of guesses N. Finally, each line gives one user input until a negative number appears.

Output format:

Output the corresponding result of each guess in one line, until the output of the correct guess or " Game Over" is over.

Input sample:

58 4
70
50
56
58
60
-2

Sample output:

Too big
Too small
Too small
Good Guess!

Code:

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

int main() {
    
    
	int random,N,i = 1,num,chances = 0;
	scanf("%d %d",&random,&N);
	while (i <= N) {
    
    
		scanf("%d",&num);
		if (num < 0) {
    
    
			printf("Game Over\n");
			chances += 1;
			break;
		}else {
    
    
			// 猜中的情况 
			if (num == random) {
    
    
				chances += 1;
				if (chances == 1) {
    
    
					printf("Bingo!\n");
				}else if (chances <= 3) {
    
    
					printf("Lucky You!\n");
				}else {
    
    
					printf("Good Guess!\n");
				}
				break;
			}else if (num > random) {
    
    
				printf("Too big\n");
				chances += 1;
			}else {
    
    
				printf("Too small\n");
				chances += 1;
			}
		}
		if (chances >= N) {
    
    
			printf("Game Over\n");
			break;
		}
	}
	return 0;
}

Submit screenshot:

Insert picture description here

Problem-solving ideas:

There are many situations to consider here, it is recommended to write one by one, don't confuse yourself! One thing to note is that over Ntime guess that does not count, that is chances >= Nwhen we will have a nominal output Game over!and then break;out of the loop!

Guess you like

Origin blog.csdn.net/weixin_43862765/article/details/114479100