0

So this program is supposed to guess a number which you though in your mind. But if you run it and see after asking you the first question it doesnt take anymore input.

#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;

}

F_J
  • 3
  • 4
  • so how do I fix that? – F_J Mar 02 '17 at 15:30
  • That question has 10 (!) answers. – Eugene Sh. Mar 02 '17 at 15:31
  • You can find a lot of answer for your question on stackoverflow itself as Eugene Sh told . But if still you want to fix it in your existing code then use scanf("%*c%c", &ans); Have a look: http://stackoverflow.com/questions/1669821/scanf-skips-every-other-while-loop-in-c – vinod maverick Mar 02 '17 at 15:49

2 Answers2

0

Try this:

scanf(" %c", &ans);

Instead of

scanf("%c", &ans);
msc
  • 33,420
  • 29
  • 119
  • 214
0

I think you are looking for a program to guess a number, but your code doesn't seems to be optimal way. It is possible to do it in one loop and three if-else statement: if matches print "Congratulation" and break the loop, else look for changing the upper limit or lower limit.

Try something like this:

#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;   
}

In case you want to stick to your code, I would suggest you to use getchar() function instead of scanf("%c", &ans). You can understand more about it from this link

Bidisha Pyne
  • 543
  • 2
  • 13
  • I tried it as shown in the example in the link but it didnt work. Thanks for the help tho. – F_J Mar 02 '17 at 16:32