srand(time(NULL)) in C++ [duplicate] - c++

This question already has answers here:
Problems when calling srand(time(NULL)) inside rollDice function
(3 answers)
Closed 9 years ago.
If I comment out the line with srand, the program will work, but there is no seed so the values will be the same each time. The assignment requires that I use rand, srand, and time to have the dice function be completely random.
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;
int rollDice();
// function declaration that simulates the rolling of dice
int main() {
int roll1 = rollDice();
int roll2 = rollDice();
// define, initialize, and combine dice roll total
int total;
total = 0;
total = roll1 + roll2;
* this is where a bunch of stuff is output to the screen from the dice rolls, using total as well as some other stuff that is being calculated, i left it out for simplicity*
}
// function to simulate a random dice roll
int rollDice() {
int r;
srand (time(NULL));
r = (rand() % 6) + 1;
return r;
}

Put srand in the main and call it once.
You have to use the seed once to get all the results from a random sequence.
Here you restart the sequence every time you roll the dice.
See the documentation for srand()

Related

Generating two ( or multiple) uniformly distributed random numbers c++ [duplicate]

This question already has answers here:
Why does rand() return the same value using srand(time(null)) in this for loop?
(5 answers)
Closed 7 years ago.
I would like to generate several uniformly distributed random numbers in the same pass.
So far I have a "standard" function for generating a random number
double generateRandomNumber()
{
srand((unsigned)time(NULL));
double r=((double)rand()/(double)RAND_MAX);
return r;
}
how ever when in main I call it like that:
# include <iostream>
# include <string>
# include <cmath>
# include <ctime>
int main()
{
// generate random number
double rr1=generateRandomNumber();
double rr2=generateRandomNumber();
cout << rr1 << endl;
cout << rr2 << endl;
return 0;
}
I get that both numbers are the same ( I guess its the time limitations of seconds), anyways, this is something I would like to generelize to multiple random numbers.
Can anyone suggest a better way? maybe using a different method or library?
Do not call srand every time beore using rand.
srand should be call only once on the program begins.
You can use static variable to see if srand is previously called.
double generateRandomNumber()
{
static bool initialized = false;
if (!initialized)
{
srand((unsigned)time(NULL));
initialized = true;
}
double r=((double)rand()/(double)RAND_MAX);
return r;
}

Issue with Random Number Generator in a Class [duplicate]

This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 9 years ago.
First off this could be complete rubbish as I am new to C++ classes and have never used a random number generator before. But this is my attempt. It generates a random number between the values that I want, thats fine. but when outputting them via an array, all the random values are the same.
RandomNumberGenerator.h
#pragma once
#include <iostream>
#include <cstdlib>
#include <ctime>
class RandomNumber
{
public:
void randomNumber();
int actualRandomNumber;
};
RandomNumberGenerator.cpp
#include "RandomNumberGenerator.h"
void RandomNumber::randomNumber()
{
srand (time(NULL));
actualRandomNumber = rand() % 66 + 1;
}
Game.h
#include "RandomNumberGenerator.h"
class Game
{
private:
int myNumbers[6];
public:
void createGame();
};
Game.cpp
#include "Game.h"
void Game::createGame()
{
RandomNumber create;
std::cout << "Welcome to your game!" << std::endl;
for (int i = 0; i < 6; i++)
{
create.randomNumber();
myNumbers[i] = create.actualRandomNumber;
}
for (int i = 0; i < 6; i++)
{
std::cout << myNumbers[i] << std::endl;
}
}
main
#include "Game.h"
#include "RandomNumberGenerator.h"
int main()
{
Game play;
play.createGame();
system("pause");
return 0;
}
Thanks in advance for anyones time.
Everytime you call srand(time(NULL)), you set the starting point of your sequence depending on a value that only changes once a second, thus your number only changes once a second (independend from number of calls).
So only calling srand() once will fix your code.
Notice, that both rand() and your actualRandomNumber = rand() % 66 + 1; are really bad regarding their "randomness" (why).
Use the C++ STL instead, consider the example on the bottom of the page (you want the uniform int distribution).
Edit: Typo and link to OneC++ Talk
The pseudo random number generator starts with a certain number and then generates a sequence based on the first number.
When the first number is the same the output sequence will be the same.
To generate different sequences each time you launch your program, the idea is to use the starting time of your program relatively to a specific date in miliseconds.
So the Error in your code is that you placed the srand(time(NULL)) in the function randomnumber() and it's being called in the loop. Because the CPU is so fast the time(NULL) (the first number in the sequence) will return the same value in miliseconds. Thus your having the same sequence.
To solve this place srand(time(NULL)) in main()

C++ rand() keeps returning the same number

I can't figure out why my program keeps generating the same random digit for every round. In fact the number won't change unless I quit and restart the program. Since I'm new to C++, this should be a fairly trivial mistake that I don't know about. Below is my code and thanks in advance for your help.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int getRandNum();
int main()
{
int randNum = getRandNum();
srand((unsigned int) time(NULL));
.
.
.
}
int getRandNum()
{
int randNum;
randNum = rand() % 3 + 1;
return randNum;
}
You're calling your computerChoice function only once and use this result for all the subsequent operations.
Also, the call has to be done after seeding the random generator with srand, like was correctly mentioned by #ZdeslavVojkovic
You call rand from function getComputerChoice().
However, that function is called before you set the seed with srand.
You need to call srand before the first call of rand function, which also means before getComputerChoice
You need to move int computerChoice = getComputerChoice(); to inside the do loop. The code above picks one choice at the start then never picks another.
You just write getComputerChoice() below the getPlayerChoice(), and your issue is resolved.
playerChoice = getPlayerChoice();
computerChoice = getComputerChoice();
Problem in your algorithm, you calling getComputerChoice() only once at the begining of the main(), but you need to do this in your do ... while:
...
if(playQuitOption == 'p' || playQuitOption == 'P')
{
cout << endl;
playerChoice = getPlayerChoice();
computerChoice = getComputerChoice();
...

How can I generate a random number between 5 and 25 in c++ [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generate Random numbers uniformly over entire range
C++ random float
How can I generate a random number between 5 and 25 in c++ ?
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void main() {
int number;
int randomNum;
srand(time(NULL));
randomNum = rand();
}
Do rand() % 20 and increment it by 5.
In C++11:
#include <random>
std::default_random_engine re;
re.seed(time(NULL)); // or whatever seed
std::uniform_int_distribution<int> uni(5, 25); // 5-25 *inclusive*
int randomNum = uni(re);
Or it could just as well be:
std::uniform_int_distribution<int> d5(1, 5); // 1-5 inclusive
int randomNum = d5(re) + d5(re) + d5(re) + d5(re) + d5(re);
which would give a different distribution on the same range.
The C++ way:
#include <random>
typedef std::mt19937 rng_type; // pick your favourite (i.e. this one)
std::uniform_int_distribution<rng_type::result_type> udist(5, 25);
rng_type rng;
int main()
{
// seed rng first!
rng_type::result_type random_number = udist(rng);
}
#include <cstdlib>
#include <time.h>
using namespace std;
void main() {
int number;
int randomNum;
srand(time(NULL));
number = rand() % 20;
cout << (number) << endl;
}

Can I make my do while loop create a new random number every time it loops?

Can I make my do while loop create a new number from my pseudo random number every time the loop comes around again? If so, how?'
EDIT: Sorry, it's in C++
EDIT2: I just want a new number between 0 and 3 (0,1,2,3) every time the do...while loop goes around for an integer
While you might like the following example:
do
{
new_number = out_of(my_pseudo_random_number);
}
while(true);
You may find it more useful:
int main()
{
srand(time(NULL)); // Initialize once at program startup.
do
{
int number = rand(); // generate new random number,
}
while(true);
}
(But I'm absolutely not sure what your're asking for)
This will specifically make random numbers from 0 t0 3.
You don't necessarily need the iostream/cout statements except for the output I do.
rand() % 4; creates a random number from 0 to (not including) 4.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
int num;
//initialize random seed
srand(time(NULL));
//make some numbers
do{
num = rand() % 4;
cout << num;
} while(true);
return 0;
}