Reputation: 25
can any one help in this program?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
srand(time(NULL));
int r = rand();
int op = 0;
while(0==0){
printf("Enter a value\n ");
scanf("%i\n",&op);
if (op == r ){
printf("yes");
break;
}
else if( op<r)
printf("Your guess is lower than the number");
else
printf("Your guess is higher than the number");
}
printf("%i",r);
return 0;
}
when i try the program in "terminal" the result is always : Your guess is lower than the number
i don't know what's going on? but when i use code blocks in windows it seems perfect.
is this problem from Linux or the compiler
i wrote cc main.c in terminal then " ./a.out"
Upvotes: 2
Views: 409
Reputation: 110118
rand()
will return a number that is up to RAND_MAX
. This value is platform-dependent.
Using Visual C++ on Windows, RAND_MAX
is equal to 32767. However, on Linux when using the GNU C Library, it will be equal to 2147483647. So you'll have a much larger range of numbers to guess from. This is probably why you always guess numbers that are too small on Linux but not on Windows.
Note that 2147483647 is the largest possible value for an int
with gcc, so guessing higher than that will not give the correct result, because the guess won't fit in op
.
As the others have said, you should limit the value of r
to a platform-independent value, for example with rand() % 100
.
Upvotes: 2
Reputation: 23699
rand
returns a pseudo-random integer between 0
and RAND_MAX
, but RAND_MAX
can be a big number (2147483647 on my GNU/Linux). You should perform a modulo operation (%
operator).
To make sure of this, you should print the value of r
on the terminal.
Upvotes: 0
Reputation: 10093
I think you should limit the range r can belong to, using something like:
r = rand() % 100;//r will be between 0 and 99
Upvotes: 1
Reputation: 4718
It seems like your value of r
can be quite large. I am not sure why it works better in Windows, did you try it many times? It could be that you got lucky and had it generate a number which was less than you guessed. I just ran it and placed in a printout and the value was r = 1262702361
, which is quite large.
To keep the value in between, say, 1 and 100, use a mod operator. Something like r = r%100
will limit r to 1 - 100 range.
Upvotes: 1