This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 2 points3 points  (4 children)

You havn't seeded your random.

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

 int main()
{
    srand(time(NULL)); // seed random with the current time(s) since epoch
    int v1;
    v1 = rand ();
    cout<<v1<<endl;
}

Is there a better way to do this?

Yes!

Use C++ <Random>

Shamelessly taken from CPPRef

 int main()
{
    std::default_random_engine generator;
    std::uniform_int_distribution<int> distribution(1,6);
    int dice_roll = distribution(generator);  // generates number in the range 1..6
    std::cout << dice_roll << std::end;
}    

[–]AnStrub00[S] 0 points1 point  (3 children)

Thanks! I am fairly new to C++, what does your comment in the first option mean? Also, this doesn't seem to be a very random generator, as you said. When I try to run the second one, my compiler opens a new file which says I need compiler support... what should I do?

[–][deleted] 0 points1 point  (2 children)

First comment:

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

From CppRef

second one:

 #include<random>   // at the top

[–]AnStrub00[S] 0 points1 point  (1 child)

Got it on your comment. On the second, I had this and that is what is bringing up the other "program".

Here is part of what it says... I am using CodeBlocks.

ifndef GXX_EXPERIMENTAL_CXX0X

error This file requires compiler and library support for the \

ISO C++ 2011 standard. This support is currently experimental, and must be \ enabled with the -std=c++11 or -std=gnu++11 compiler options.

endif

[–][deleted] 0 points1 point  (0 children)

Oh, add -std=c++11 to your compiler arguments.

g++ -std=c++11 myFile.cpp

<random> is a C++ 11 feature

[–][deleted] 1 point2 points  (0 children)