I was wondering what the way is to get a random number with a range of 1-6, using the rand() method. This is to simulate a dice roll needed for me to find the average of 3 dice rolls so the type will be double.
This is a simple example to generate randoms between 1 to 6, I think you can figure the rest
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0));
std::cout << (rand() % 6 + 1) <<std::endl;
return 0;
}
Related
This question already has answers here:
How to generate a random number in C++?
(14 answers)
Closed 1 year ago.
I'm making a rock paper scissors bot that randomly picks rock, paper or scissors. I have an array called rpsoptions as shown below.
#include <iostream>
#include <string>
int main()
{
std::string rpsoptions[3] = {"rock", "paper", "scissors"};
std::cout << ( RANDOM ITEM FROM ARRAY) << std::endl;
}
How do I select a random element from the array?
You do this by:
Generating a random index into the array (in your case between 0 and 2); let that index be i.
Emitting rpsoptions[i].
As #ThomasSablik notes, the first step is covered by this question:
How to generate a random number in C++?
Combining the two steps, here is what you could get for your program:
#include <random>
#include <iostream>
int main()
{
std::random_device dev;
std::mt19937 randomness_generator(dev());
std::uniform_int_distribution<std::size_t> index_distribution(0,2);
std::string rpsoptions[3] = {"rock", "paper", "scissors"};
auto i = index_distribution(randomness_generator);
std::cout << rpsoptions[i] << std::endl;
}
Note that I've glossed over the issue of seeding the pseudo-random number generator; that's covered in the first answer at the link above, and would result in a bunch more code. It's important when you actually want to rely on properties of your random distribution, but not so important to illustrate the way you use the (pseudo-)randomly-generated index.
You only need to generate a random number and use it to choose the element into the array:
int main() {
srand(time(NULL));
std::string rpsoptions[3] = {"rock", "paper", "scissors"};
std::cout << rpsoptions[rand() % 3] << std::endl;
return 0;
}
where rand() % 3 generates a random integer number in [0, 2] range (number of the elements in the array you have).
hi guys i want to generate a number of matrices of 5x5 with random numbers but this code i made only prints the same matrix over and over, whats the issue? (i am learning c++), this code just print the same matrix over and over instead of being different numbers in each matrix
#include <iostream>
#include <string>
#include <sstream>
#include <ctime>
#include <iomanip>
#include <cstdlib>
using namespace std;
bool verif(int carton[5][5], int f, int c, int nume){
for(f=0;f<5;f++){
for(c=0;c<5;c++){
if(nume==carton[f][c]){
return false;
}
}
}
return true;
}
int i,cant,nume;
int main()
{
ingresa:
int j,cant;
cout<< "type the number of bingo cards you want: ";
cin>>cant;
if(cant>100){
cout<<"ERROR the max number of bingo cards is 100:"<<endl;
goto ingresa;
}
for(i=1;i<=cant;i++){
cout<<endl;
cout<< "BINGO #"<<i<<endl;
int carton[5][5];
int f,c,nume;
srand(time(NULL));
for(f=0;f<5;f++){
for(c=0;c<5;c++){
nume=1+rand()%25;
carton[f][c]=nume;
while(verif(carton,5,5,nume)==false){
nume=1+rand()%25;
}
carton[f][c]=nume;
}
}
for(f=0;f<5;f++){
for(c=0;c<5;c++){
cout<<setw(3)<<carton[f][c]<<" ";
}
cout<<endl;
}
}
}
The main problem is that you call srand() multiple times, resetting the state of the random number generator to the same value (unless you are lucky and the clock steps a second between iterations). You should only seed the pseudo random number generator once.
Minor details:
Your algorithm for filling the array is expensive. Instead of generating a random number and testing if that number is already taken, generate the numbers in order (1-25) with std::iota and then std::shuffle the array.
Don't use srand() & rand(). There are much better random generators in the standard library, like std::mt19937
Don't use goto. Make a while(true) loop and break out of it when the user has entered a valid number.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
int main() {
std::mt19937 prng(std::random_device{}()); // A seeded PRNG
int carton[5][5];
// fill the array with 1-25
std::iota(&carton[0][0], &carton[0][0] + 25, 1);
// make the order properly random
std::shuffle(&carton[0][0], &carton[0][0] + 25, prng);
// You can use the prng to generate a random number in the range [1,25]
// with the help from uniform_int_distribution:
std::uniform_int_distribution<int> dist(1, 25);
std::cout << "A random number 1-25: " << dist(prng) << '\n';
}
This question already has answers here:
Generate random numbers using C++11 random library
(6 answers)
srand() — why call it only once?
(7 answers)
Closed 3 years ago.
I am trying to use the rand() which can generate a random number. However, I found that the code keep giving the same number when every time I compile it.
Here is the code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int a = rand() % 11;
cout << a;
return 0;
}
What you can do is include the:#include<time.h> and use srand at the top of main. This will correct this issue because it will specify the seed for the generator.
// top of main
srand(static_cast<unsigned int>(time(0)));
time(0) provides you with the seconds that have passed since Jan 1, 1970. This provides a good seed.
When you have time look into the <random> header here
You have to seed it at least 1 change to get random numbers every time you run the file:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(0));
int random = rand();
cout << "Seed = " << time(0) << endl;
cout << "Random number = " << random << endl;
return 0;
}
I'm trying to get randomly generated numbers by using srand() and rand() but with no avale: every time I run the program it increases by a certain amount of numbers. But if I use a for statement, no pattern can be seen.
For example, if I use the code provided below and run and close the program 10 times, the output will be:
42
52
72
78
85
92
12 (it has reset)
32
48
Note: one strange thing I noticed about this that when I unfocus or minimize Visual Studio and close the Command Prompt, the next time I run the program the number increases by more than 20, but, if I don't unfocus or minimze Visual Studio the number increases by just little over 1-5. Why's that?
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(NULL));
int random_number = rand () % 100 + 1;
cout << "Random number: " << random_number << endl;
return 0;
}
But, if I use this code:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(NULL));
for (int i = 0; i < 10; i++) {
int random_number = rand () % 100 + 1;
cout << "Random number: " << random_number << endl;
}
return 0;
}
the numbers don't have a clear pattern and I get the output:
31
10
81
66
74
14
6
97
39
23
They increase and decrease randomly by random amounts. What seems to be the problem here?
The first few random numbers returned by some versions of rand (looking at you Microsoft) are highly correlated to the seed they start with, just due to the random number generator formula being used. Since the time isn't changing much between runs, neither do the random numbers. If you throw away the first few random numbers that get returned you can get much better results.
A better solution is to use std::uniform_int_distribution instead of rand.
Another potential issue is some implementations of rand may interact poorly with certain modulos. For that reason you may want to consider something like this instead:
int v = ((double)rand() / (double)RAND_MAX) * 100 + 1;
Still not ideal, but easy.
There will be two numbers in the input file which are between 1 ≤ n, m < 100.
I should display m to power n. When i use pow(x,y) function it cannot calculate big integers for ex ::: 12 to power 23 normally should show 6624737266949237011120128, but my code displays negative number. Can anyone solve this exercise ?
This is not very difficult to do without using external libraries. Store the digits of the number in a vector and multiply digit by digit (like you do in paper).
Example:
power(12,23):
Store as start->1->2->end
step 1 result: start->1->4->4->end
step 2 result: start->1->7->2->8->end
and so on...
Can you show your source code?
Use double is enough to store the result
Below is my test code for you reference:
#include <iostream>
#include <cmath>
using namespace std;
int main (int argc, char *argv[])
{
double result = pow (12, 23);
cout.precision (26);
cout << "Result: " << result << endl;
}
Try to store your base in a long double before calling pow :
long double base = 12;
long double result = pow(base, 23);
It is not required since C++11 though, you can get a good approximation like this :
#include <iomanip>
#include <iostream>
#include <cmath>
int main ()
{
std::cout << std::fixed << std::setprecision(0) << pow(99, 99) << std::endl;
}
Output :
369729637649726802192985226395427290145296428445515959701359650120802601667133273280053721002700400354392780458116125965728631706472588849812738072765460822138161108630185181415759762204338929270784
But it is an approximation, for instance Python2 code print 99 ** 99 outputs this :
369729637649726772657187905628805440595668764281741102430259972423552570455277523421410650010128232727940978889548326540119429996769494359451621570193644014418071060667659301384999779999159200499899
To get an exact result in C++, you should look at some BigInt libraries.