random number between 0 and 1: C vs C++11, C wins?

Hey guys,

I want a function to get random numbers between 0 and 1.
I tried it c-style with rand and c++11-style with a default_random_engine

I came to the conclusion that the default_random_engine allways gives the same random numbers when I restart the programm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Example program
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <random>

float rand1()
{
    return float(rand()) / RAND_MAX;
}
float rand2()
{		
    static std::default_random_engine generator;
    static std::uniform_real_distribution<float> distribution(0.0,1.0);
    return distribution(generator);
}

int main()
{
    srand(time(0));
    
    std::cout << rand1() << std::endl;
    std::cout << rand2() << std::endl; // allways gives me 0.131538
}

http://cpp.sh/722l

Am I doing something wrong?
How can I fix this?

- Gamer2015
You never gave it a seed.
+1 Ispil

Seed 'generator' the same way you seed srand:

 
static std::default_random_engine generator(time(0));
hm... interesting that I never came across that...
thank you!
Topic archived. No new replies allowed.