I create a simple game to make the user guess a random number from 1 to 10. It worked fine and then I tweaked it to where I made a function that took 2 arguments, a high and low value, to generate a random number. Doing this through the function always returns the value of the highest number entered as an argument when it should return a random number. Here is my code:
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
int main(void) {
int storedNum, low, high, userGuess;
printf("Welcome to my random numbers game! You will choose a lower number and a maximum number and me, the computer, will choose a random number between those two values for you to guess.\n\nFirst, choose the lowest value");
scanf("%d", &low);
printf("Now, choose the highest value");
scanf("%d", &high);
storedNum = randomNumbers(low, high);
printf("We have guessed a number between %d and %d. Guess our number!: ", low, high);
scanf("%d", &userGuess);
while (userGuess != storedNum){
if(userGuess < storedNum){
printf("higher!: ");
scanf("%d", &userGuess);
}
else{
printf("Lower!: ");
scanf("%d", &userGuess);
}
}
printf("You are correct the number was %d!", storedNum);
return 0;
}
int randomNumbers(int maxNum, int minNum){
int number;
srand(time(NULL));
number = rand()%maxNum + minNum;
return number;
}
The code works fine as long as I generate my random number within the main method, but whenever I use it through a function I always get the same return value. I think the problem lies within the seed being inside the function, but I am not entirely sure. Even if that was the issue I am not sure how I would fix that and get my code working.
Basically, I am trying to write a function that I can reuse in other programs to generate a random number between x and y.
here is some sample output:
Welcome to my random numbers game! You will choose a lower number and a maximum number and me, the computer, will choose a random number between those two values for you to guess.
First, choose the lowest value 1
Now, choose the highest value 10
We have guessed a number between 1 and 10. Guess our number!: 5
higher!: 8
higher!: 9
higher!: 10
You are correct the number was 10!
No matter what numbers I enter it always returns the max value (in this case 10). Thanks in advance for any and all help and I hope this post finds you well.
Aucun commentaire:
Enregistrer un commentaire