# [C++] Random Number generation problems



## dmneoblade (Apr 15, 2004)

Can someone help me figure out how to make this program output Random Numbers? I tried the srand(time(NULL)) trick, but it just repeats the same number! I want to keep all the stuff in the dicegen(int) function if possible, and keep it out of the main() function.


----------



## Shadow2531 (Apr 30, 2001)

You need to use a different seed value each time the function is called or you'll get both dice = the same.


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

using namespace std;

int dicegen_rolldice(int sides, int i) {
    int roll;
    int seed = i; 
    srand(seed);
    roll = 1 + (rand()%sides);
    return roll;
}

int main() {
    cout << "How many dice do you want to roll?" << endl;
    int dice;
    cin >> dice;
    cout << "How many sides do the dice have?" << endl;
    int sides;
    cin >> sides;
    int total = 0; 
    int roll;
    cout << "Rolling " << dice << "d" << sides <<":\t" << endl; 
    for(int i = 1; i <= dice; i++) {
       roll = dicegen_rolldice(sides,i); 
       cout << roll << "\t"; 
       total += roll;
    }   
    cout << endl << "The total is: " << total << endl << endl;
}
```
Since the value of i changes each time through the loop, you can use it to seed srand with a different value each time it is called.

There may be more to fix, but that should help.

Also consider that for a die to be 3-dimensional, it needs a minimum of 4 sides.


----------



## Shadow2531 (Apr 30, 2001)

I forgot to mention that I understand that your time(NULL) is supposed to do exactly what I suggested, but the loop operation is faster than that, so srand() still gets seeded with the same time value.


----------



## kripto666 (Feb 6, 2004)

srand(time(0));


rand() % 8

should work, but idunno


----------

