我刚刚开始学习C编程,并且为了锻炼,我找到了这个任务。这是一个数字猜谜游戏,计算机在其中猜测我所记的数字。首先,我必须考虑一个数字。然后,我必须在数字范围内进行扫描。然后计算机生成该范围内的数字,并问我它是否正确。根据计算机的答案,如果L值太低,我必须回答L;如果L值太高,我必须回答H;如果正确,则回答G。如果正确,则将其打印出来,并打印尝试次数。如果输入了其他任何字符,则会打印出我输入了错误的答案。
这就是我到目前为止所得到的。它没有给我任何错误,但是当我输入L,H或G时,它会打印出我输入了错误的答案。
在此先感谢您的帮助。
#include<stdio.h>
#include<stdlib.h>
void main(){
int randomNo = 0;
int input = 0;
int counter = 0;
int min = 0;
int max = 0;
char answer = ' ';
char low = 'L';
char high = 'H';
char good = 'G';
printf("Enter min and max: ");
scanf_s("%d %d", &min, &max);
do{
randomNo = min + rand() % (max - min) + 1;
printf("Is it %d?\n", randomNo);
printf("Enter your answer:");
scanf_s("%s", &answer);
if (answer == low){
printf("Number guessed is low\n");
min = randomNo;
counter++;
}
else if (answer == high){
printf("Number guessed is high\n");
max = randomNo;
counter++;
}
else{
printf("You entered the wrong answer!\nYour answer should be L - too low H - too high G - goed\n");
}
} while (answer != good);
printf("Your answer is correct!\nYou guessed it in %d times!\n", counter);
}
代替
scanf_s("%s", &answer);
使用:
scanf_s(" %c", &answer);
正如answer
不是字符串,而是字符。
您还需要更改else
为else if(answer != 'G')
或else if(answer != good)
。rand
也会产生相同的值。为了生成随机值,您需要
srand(time(NULL));
在开始时main
。这是伪随机数生成器
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句