-3

So far, I have made a program that creates a random number using srand and rand.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

    srand(time(0));

    for(int x = 1; x<25;x++) {
        cout << 1+ (rand()%6);
    }

}

How do I store the random number using int?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • 1
    Use a `int` variable? Where do you want to _store_ it actually? – πάντα ῥεῖ Sep 20 '15 at 20:32
  • You're already storing a value in an `int` with `x`. It's no different. – chris Sep 20 '15 at 20:32
  • 2
    The same way you store any `int`. If you don't know how to do that, you *really* need to read a [C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Learning C++ by trial and error does not work at all. – Baum mit Augen Sep 20 '15 at 20:32
  • 1
    You store a random number the exact same way you do a deterministic one - you assign it to a variable of appropriate type. – Igor Tandetnik Sep 20 '15 at 20:32
  • 1
    Not sure what you mean by "store". In a database? In a variable? In a file? – Vaughn Cato Sep 20 '15 at 20:32
  • 1
    Simply `int k=1+rand()%6` – ForceBru Sep 20 '15 at 20:33
  • 1
    @Allister - It looks like you're trying to store 25 random integers, no? If you want to just store one, you can just use: `int x = rand(0, 6)` or something along those lines – Phorce Sep 20 '15 at 20:33
  • `rand()%6` has distribution issues that are't very random. Take a look at [uniform_int_distribution](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) as a replacement. It's longer winded, to set-up, but the results are much better. – user4581301 Sep 20 '15 at 21:09
  • I want to store it as a variable. –  Sep 21 '15 at 19:42

1 Answers1

4

How do I store the random number using int?

As mentioned in my comment, that's simply done assigning an int variable instead of outputting it:

int myRandValue = 1+ (rand()%6);

But it sounds like you want to have the whole set of generated values available for use after generating them.

You can simply store your random numbers in a std::vector<int> like this:

std::vector<int> myRandValues;
for(int x = 1; x<25;x++) {
    myRandValues.push_back(1+ (rand()%6));
}

and later access them from another loop like

for(auto randval : myRandValues) {
    cout << randval << endl;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190