#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generates and prints 'count' random numbers in range [lower, upper].
void printRandoms(int lower, int upper, int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() % (upper - lower + 1)) + lower;
printf("%d", num);
}
}
int main()
{
int lower = 5, upper = 7, count = 5;
srand(time(0));
printRandoms(lower, upper, count);
return 0;
}
#How do I make a variable return a random number from this code?
11 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
This is the main program that I'm trying to turn the random number into a variable for
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int yourGuess;
int guessesMade = 0;
int totalNumberOfGuesses = 3;
int outOfGuesses = 0;
int main()
{
void printRandoms(int lower, int upper, int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() % (upper - lower + 1)) + lower;
}
}
int lower = 5, upper = 7, count = 1;
srand(time(0));
printRandoms(lower, upper, count);
int correctNumber = num;
while(yourGuess != correctNumber && outOfGuesses == 0) {
if(guessesMade < totalNumberOfGuesses) {
printf("Guess the correct number: ");
scanf("%d", &yourGuess);
guessesMade++;
} else {
outOfGuesses = 1;
}
}
if (guessesMade == totalNumberOfGuesses) {
printf("Sorry, but you have run out of guesses. You lose!");
} else {
printf("You guessed the correct number! You win!");
}
return 0;
}
And here's what the main program looked like before I modified it
#include <stdio.h>
#include <stdlib.h>
int currentGuess;
int correctNumber = 18;
int totalNumberOfGuesses = 3;
int guessesMade = 0;
int outOfGuesses = 0;
int main(){
while (currentGuess != correctNumber && outOfGuesses == 0){
if(guessesMade < totalNumberOfGuesses){
printf("Hello! Please choose a number between 1 and 25: \n");
scanf("%d", ¤tGuess);
guessesMade++;
} else {
outOfGuesses = 1;
}
}
if(outOfGuesses == 1){
printf("Sorry, you have run out of attempts. The correct number is: %d. You lose.", correctNumber);
} else {
printf("Congratulations, you have guessed the correct number. You win!");
}
return 0;
}
Thank you and let us know if you have any more questions!
This thread is now set to auto-hide after an hour of inactivity
Read from /dev/urandom?
Join a server;
Ask a question;
Wait an hour;
Rage quit. 
is there any difference between /dev/random and /dev/urandom ?
Random is more secure but slower