0

I'm trying to use a custom function to make generating random numbers easier. It only works 50%, as it will generate a random number, but when used in a loop, it generates the same random number over and over again.

I had one result where the first number was different, but the 9 that followed were the same. I was unable to reproduce this outcome.

I want each number to completely different.

Code:

#include <iostream>
#include <cstdlib>
#include <ctime>

int randomNumber(int x, int y) {
    srand(time(0));
    return x + (rand() % y);
}

int main() {

    for (int i = 0; i <= 10; i++) {
        std::cout << randomNumber(1, 100) << std::endl;
    }

    return 0;
}

Possible Outcome:

37
37
37
37
37
37
37
37
37
37

Desired Outcome:

1
47
32
56
82
// and so on...
Bellator
  • 352
  • 1
  • 3
  • 11
  • You may find the linked video very informative (and more than a little funny): [Rand considered harmful](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) – user4581301 May 03 '19 at 01:49
  • @user4581301 I'm watching it right now and I'm actually quite entertained/relieved that a man could stand up there and tell jokes about programming in a room full of people who actually understand the jokes. – Bellator May 09 '19 at 13:25

0 Answers0