replay the game does not work.It can not recognize “n” when you want to quit. in
ID: 2247420 • Letter: R
Question
replay the game does not work.It can not recognize “n” when you want to quit. include int main (int argc, char **argv) t int a 1; number between 1 and 100 and press "); while (a){ printf("Thinkf int high=100; int low=1; a char str; while (high >= low) { getchar) int mid= (high + low) / 2; printf ("Is it higher than d? y/n)n",mid) scanf (&str;) if ( str=-'y ') { low= (mid+1 ) ; } else if ( str== 1 n' ) { high= (mid-1); }else {printf ("Type yar n"); printf(" >>>>>> The number is %d ",high+1); to continue playing (y/n) ?1n) printf ("Do you want scanf ( "%c", &str;) ; getchar ) if ( str== n' ) { a=0; } ("Thanks for playing!!!")Explanation / Answer
just put a space before %c in scanf statements as it takes as the character input by using return statement. Space will consume that newline character.
#include <stdio.h>
int main(void)
{
int a = 1;
while(a)
{
printf(" Think of a number between 1 and 100 and press <enter> ");
int high = 100;
int low = 1;
char str;
while(high >= low)
{
getchar();
int mid = (high + low)/2;
printf("Is it higher than %d? (y/n) ",mid);
scanf(" %c",&str);
if(str == 'y')
low = mid+1;
else if(str == 'n')
high = mid - 1;
else
printf("Type y or n");
}
printf(" >>>>>>>The number is %d ",high+1);
printf(" Do you want to continue playing(y/n) ");
scanf(" %c",&str);
getchar();
if(str == 'n')
a = 0;
}
printf(" Thanks for playing");
return 0;
}
Output:
Think of a number between 1 and 100 and press <enter> 45
Is it higher than 50? (y/n)
Type y or n n
Is it higher than 50? (y/n) n
Is it higher than 25? (y/n)y
Type y or n y
Is it higher than 25? (y/n)
Is it higher than 37? (y/n)
Type y or n y
Is it higher than 37? (y/n)
Is it higher than 43? (y/n)
Type y or n Is it higher than 43? (y/n)
Is it higher than 40? (y/n)
Is it higher than 38? (y/n)
>>>>>>>The number is 38
Do you want to continue playing(y/n)
Thanks for playing
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.