我让我的程序完全正常工作,除了我需要程序在5次尝试失败后停止询问。我完全不知道如何去做。假设要做的是,如果输入的数字连续5次不正确,那么最后会有一条抱歉的消息。我无法弄清楚如何将计数器插入代码中,我知道我放入的内容可能远远不够正确。
P.S。代码必须具有多个功能。有些我宁愿自己加入一个,但说明多说。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int number;
void welcomeMessage(){
printf("Welcome to my new guessing game!\n");
printf("Let's get started!\n");
}
int randomNumber(int number){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return number;
}
int guessInput(){
int guess;
printf("I'm thinking of a number between 1 and 20.\n");
printf("Care to give it a guess? Be careful! You only get 5 tries!: ");
scanf("%d", &guess);
return guess;
}
int guess_input(){
int guess;
scanf("%d", &guess);
return guess;
}
int wrongAnswer(int guess){
if(guess < number)
{
printf("Try again, your guess is too low: ");
return 1;
} else if(guess > number) {
printf("Give it another try, your guess was a bit too high: ");
return 1;
}
return 0;
}
int correctAnswer(int guess){
if(guess == number){
printf("Great job! That time you got it right!\n");
return 0;
} else{
return 1;
}
}
void sorryMessage(int number){
printf("Sorry, the correct number was %number.\n");
printf("Better luck next time!");
}
int main(){
int number;
int loopCount = 5
int guess;
int correct_answer = 1;
int wrong_answer = 1;
welcomeMessage();
number = randomNumber();
guessInput();
do {
correct_answer = correctAnswer(guess);
wrong_answer = wrongAnswer(guess);
guess = guess_input();
}
while(correct_answer == 1);
if(loopcount = 5){
sorryMessage
}
return 0;
}
答案 0 :(得分:0)
我对您的程序进行了少量更改,以使其按预期编译和运行。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int number;
void welcomeMessage(){
printf("Welcome to my new guessing game!\n");
printf("Let's get started!\n");
}
int randomNumber(){
int range;
srand((int)time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return number;
}
int guessInput(){
int guess;
printf("I'm thinking of a number between 1 and 20.\n");
printf("Care to give it a guess? Be careful! You only get 5 tries!: ");
scanf("%d", &guess);
return guess;
}
int guess_input(){
int guess;
scanf("%d", &guess);
return guess;
}
int wrongAnswer(int guess){
if(guess < number)
{
printf("Try again, your guess is too low: ");
return 1;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit too high: ");
return 1;
}
return 0;
}
int correctAnswer(int guess){
if(guess == number){
printf("Great job! That time you got it right!\n");
return 1;
} else{
return 0;
}
}
void sorryMessage(int number){
printf("Sorry, the correct number was %d\n",number);
printf("Better luck next time!");
}
int main(){
int number;
int loopCount = 0;
int guess;
int correct_answer;
int wrong_answer;
welcomeMessage();
number = randomNumber();
do
{
loopCount += 1;
if( loopCount > 5)
{
sorryMessage(number);
break;
}
guess = guessInput();
correct_answer = correctAnswer(guess);
wrong_answer = wrongAnswer(guess);
} while( !correct_answer );
return 0;
}