Programming in C, I am trying to run a game where the computer generates a number between 1 and 100. However, I keep getting 42 as the number generated... what is wrong with my "rand()"
#include <stdlib.h>
#include <stdio.h>
int main (void)
{
int guess, tries = 6;
int number = 1+(rand()%100);
printf("Pick a number between 1 and 100:");
scanf_s("%d", &guess);
while(tries > 0 && guess != number)
{
if(guess > number)
printf("Too high");
else
printf("Too low");
puts(". Guess again:");
scanf_s("%d",&guess);
tries--;
}
if(guess == number)
puts("You win!");
else
puts("You lose");
}
after a good amount of discussion below I added in the fallowing lines of code
#include <time.h>
and
srand ((unsigned int)time(NULL));
but the code failed to run in MS visual studio until i googled the error and it turns out that MSVS needs the variebles to be declared at the top of each function/block. after doing this the code works fine. Thank you everyone and sorry for the multiple edits. corrected code:
#include <time.h>
int main (void)
{
int guess, tries = 6, number;
srand ((unsigned int)time(NULL));
number = 1+(rand()%100);
The rest is the same. Thank you all.