-3

Is there an alternative to rand()?Since rand()(at least for me)is freaking broken.So if you know an alternative to rand() in c++ please tell me.Since every time i run this simple code:

Code:

#include <iostream>
#include <cstdlib>

using namespace std;

void Gla()
{
  int L;
  L = rand();
  while(1)
  {
      cout<<L<<endl;
  }
}


int main()
{
    Gla();
    return 0;
}

It continously outputs 41, i don't know why it just does.

  • 4
    Maybe put the assignment for L inside the loop so you get a new random number each pass? – Eric Dec 21 '16 at 22:23
  • You may initialize the stdio generator with srand() see http://www.cplusplus.com/reference/cstdlib/srand/ You could use something like clock() to initialize the seed. see http://www.cplusplus.com/reference/ctime/clock/ Also, of course, using c++11 you have access to real c++ random number generator see http://www.cplusplus.com/reference/random/ – Bamaco Dec 21 '16 at 22:28
  • 2
    Reopened. This isn't a duplicate of the question about `srand`. In fact, it's not about `rand()` at all; it's about the meaning of assignment operations. – Pete Becker Dec 21 '16 at 23:02
  • 1
    http://xkcd.com/221/ – Matteo Italia Dec 21 '16 at 23:04
  • 1
    Downvoters: this is a legitimate question, and it reflects a very common beginner's confusion. – Pete Becker Dec 21 '16 at 23:25

1 Answers1

2

This has nothing to do with rand(). The problem is that the code assigns a value to L, then enters the loop, writing the (same) value of L multiple times. Keep in mind, once you assign a value to a variable, it holds that value until you change it. So change your function from

void Gla()
{
  int L;
  L = rand();
  while(1)
  {
      cout<<L<<endl;
  }
}

to

void Gla()
{
  int L;
  while(1)
  {
      L = rand();
      cout<<L<<endl;
  }
}

That way, the value of L gets updated each time through the loop.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165