Hi all. I decided to give C a go, and so I started to reproduce my very first QBASIC program - a simple guess the number game.
Seemed to go pretty well, except I'm having troubles getting random numbers. I understand that I need to use srand() to initialize a seed, and its common to put time() in there. However, no matter what I do I cannot seem to get different results.
Here's my code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand((unsigned)time(NULL)); // seed random number generator with time (to get pseudo random numbers)
int randomnumber = (10*rand()/(RAND_MAX+1.0)); // get a number between 1 and 10
int count = 0;
for (int usernumber; usernumber != randomnumber;) {
printf("Guess the number.\n");
scanf("%d",&usernumber); // get the guessed number
count++;
if (usernumber == randomnumber) { // if they guessed it
break;
}
if (usernumber < randomnumber) { // too low
printf("Nope. Too low...try again. You have made %d guesses.\n", count);
}
if (usernumber > randomnumber ) { // too high
printf("Nope. Too high... try again. You have made %d guesses.\n", count);
}
if (count > 4) { // if they havn't guessed it 5 times, give em a hint (tell them the number).
printf("Hint: The number is %d\n",randomnumber);
}
}
printf("You guessed the number in %d tries!", count); // final output.
}
I've tried using just srand(time()); and various combinations, but nothing.
The strange thing is - and I think this is related to time() - is that at different times (like seperated by hours) I get different numbers. For example, right now the random number is 3. Every time I run it. But a few hours ago it was 4. Maybe this is due to the way I'm getting my random number? I'm not entirely sure on the way that code works.
I'm using lcc-win32 to compile. It seems nice, I wish I could integrate jEdit with lcc's compiler (so I dont have to use lcc's IDE); are there any better options?
Edit: I did my best to search the forum for this, but I could find no problem similar. If this is a common problem, I apologize, looks like you guys get a lot of repeat questions...