所以这个程序应该猜测你想到的数字。但是如果你运行它并在问你第一个问题之后再看,它就不再需要输入了。
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("Enter the upper limit for the range of numbers:\n");
int n;
scanf("%d", &n);
int low=0;
int high=n;
printf("Answers should only be y for yes or n for no.\n");
do{
int median;
median=(high+low)/2;
printf("Is your number greater than %d median?\n", median);
char ans;
scanf("%c", &ans);
if(ans=='y' || ans=='Y'){
low=median;
continue;
}
else{
printf("Is your number smaller than %d median?\n", median);
scanf("%c", &ans);
if(ans=='y' || ans=='Y'){
high = median;
continue;
}
else
{
low = high = median;
}
}
}while(low != high);
printf("Your number is: %d\n", low);
return 0;
}
答案 0 :(得分:0)
试试这个:
scanf(" %c", &ans);
而不是
scanf("%c", &ans);
答案 1 :(得分:0)
我认为您正在寻找一个猜测数字的程序,但您的代码似乎不是最佳方式。可以在一个循环和三个if-else语句中执行:如果匹配打印“祝贺”并打破循环,则查找更改上限或下限。
尝试这样的事情:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int random_num = 0;
int guessed_num = 0;
int counter = 0;
int lower = 0;
int upper;
printf("Enter the upper range: ");
scanf("%d", upper);
srand(time(NULL));
random_num = rand() % upper + 1;
printf("Guess my number! ");
while(1)
{
counter++;
scanf("%d", &guessed_num);
if (guessed_num == random_num)
{
printf("You guessed correctly in %d tries! Congratulations!\n", counter);
break;
}
if (guessed_num < random_num)
printf("Your guess is too low. Guess again. ");
if (guessed_num > random_num)
printf("Your guess is too high. Guess again. ");
}
return 0;
}
如果您想坚持使用代码,我建议您使用getchar()
函数代替scanf("%c", &ans)
。您可以从link