#include <stdio.h>
#include<stdlib.h>
int main (){
int guess, maxGuess = 10;
int goal = rand()%50+1;
for (int i = 0 ; i<maxGuess;i++){
printf("Enter a guess between 1-50:\n");
scanf("%d",&guess);
if (guess<goal){
printf("Too low\n");
}
else if(guess>goal){
printf("Too high\n");
}
else if (guess == goal){
printf("Correct! the number was %d\n",goal);
}
}
//printf("Too many guesses, the number was %d\n",goal);
return 0;
}
this my code for a guessing game , and when it runs through it will give me the same number , for example when compiled it kept giving me 34 ,the random number kept generating 34. I cannot seem to find what I did wrong , maybe i have something in the wrong place I am not to sure I commented out the last line to see if it would help but did not, but I have looked and I haven't found anything really similar to my question so any help is appreciated!
TIA
转载于:https://stackoverflow.com/questions/53111827/random-function-stuck-on-one-number
You never seed the random number generator.
If rand
is called before calling srand
, the random number generator is seeded with 1. So you get the same number every time.
Call srand
once at the start of your program to seed the random number generator.
srand(time(NULL));
int goal = rand()%50+1;