Manuel Medina
Manuel Medina

Reputation: 409

Why is this random generator not working?

Every time I run this code it returns this value: 1804289383 If I move the body of random() inside main() it runs just fine.

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

int random(int);

int main()
{

    cout << random();
    cin.get();
    return 0;
}

int random(int) 
{
    unsigned seed = time(0); 
    srand(seed);              

    int randomNum = rand()%4 + 1;
    return randomNum;
}

Upvotes: 1

Views: 302

Answers (1)

NPE
NPE

Reputation: 500167

The problem is that random() expects an argument, and you're not supplying the argument.

If you call it like so:

cout << random(0);

it'll work.

A better approach, however, would be to eliminate the argument since it's unused.

Last but not least, you should only call srand() once, on program startup.

Upvotes: 2

Related Questions