Help With Functions and Rand

Instructions:

Write a function that returns sum of two dice rolls. A dice roll is a random number between 1 and 6. Demonstrate your function be calling it 5 times from main(). Place the function definition below main() and a function prototype above main().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void tworolls();

int main(void)
{
    tworolls();
    tworolls();
    tworolls();
    tworolls();
    tworolls();
    srand(time(0));
    int die1;
    int die2;
    die1 =  1 + rand() % 6;
    die2 =  1 + rand() % 6;

    return 0;
}



void tworolls()
{   srand(time(0));
    int die1;
    int die2;
    die1 =  1 + rand() % 6;
    die2 =  1 + rand() % 6;
    cout << die1 + die2 << endl;

}



I am having trouble getting random numbers for all of them and also don't know how to return the sum of the dice rolls.

Last edited on
You should have a loop in your
tworolls()
function

1
2
3
4
5
6
7
int die1;
int die2;
for(int index = 0; index < 5; index++){
     die1 =  1 + rand() % 6;
     die2 =  1 + rand() % 6;
     cout << die1 + die2 << endl;
}


In your main all you need essentially is
1
2
3
srand(time(NULL)); 
tworolls();
return 0;

http://www.cplusplus.com/forum/beginner/22286/
This link helps explains RNG seed
rand() is poor quality randomness but its not "harmful" in the normal sense of the term (consider the functions that had to have a safe version added to prevent hacks and security risks).

Line 15: You are seeding the random number generator AFTER you doing your dice rolls. You should be seeding it BEFORE.

Lines 16-19: What's the point of these lines? You don't do anything with the result of the rolls.

Line 27: Do not call srand() multiple times. srand() sets the RNG to a particular starting point. Calling srand() repeatedly can cause the RNG to return the same random numbers. srand() should be called ONCE at the beginning of main().
http://www.cplusplus.com/reference/cstdlib/srand/

@hengry - If anything, the for loop should be in main. The instructions specifically state to call the function 5 times. Placing the for loop inside the tworolls function does not meet that requirement.
Last edited on
Topic archived. No new replies allowed.