#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int guessGame(int guessed_num){
int counter = 0;
int random_num = 0;
while(1)
{
counter++;
if (guessed_num == random_num)
{
printf("Correct! That's the number.\n", counter);
break;
}
if (guessed_num < random_num)
printf("Too low. Guess again.\n");
if (guessed_num > random_num)
printf("Too high. Guess again.\n");
}
}
int main(){
int guessed_num = 0;
srand(time(NULL));
int random_num = rand() % 50 + 1;
printf("I have a number between 1-50.\n");
printf("Can you guess what it is?\n");
printf("Enter your initial guess.\n");
scanf("%d", &guessed_num);
printf("%d\n" ,guessGame(guessed_num));
return 0;
}
所以我必须做一个猜谜游戏,用户必须正确猜测一个随机创建的整数。问题是,我必须使用一个函数来运行实际的猜谜游戏。我被卡住了,因为我不知道如何正确调用我的功能。我知道我的main函数中的printf语句不是正确的方法。
答案 0 :(得分:0)
由于您只想打印猜测状态(太高,太低等),具体取决于用户输入的单个参数,因此您无需在功能中使用while循环。以下代码将有所帮助:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int random_num;
void guessGame(int guessed_num){
if (guessed_num == random_num)
printf("Correct! That's the number.\n", guessed_num);
else
if (guessed_num < random_num)
printf("Too low. Guess again.\n");
else
printf("Too high. Guess again.\n");
}
int main(){
int guessed_num = 0;
srand(time(NULL));
random_num = rand() % 50 + 1;
printf("I have a number between 1-50.\n");
printf("Can you guess what it is?\n");
while(1){
printf("Enter your initial guess.\n");
scanf("%d", &guessed_num);
guessGame(guessed_num);
}
return 0;
}