-1

I am doing a school assignment and don't know how to proceed without knowing how to do what I asked in the title. I was given code (by my prof) to run and print a dice roll (1-6).

void showDice (int num) {
     int diceRoll;
     srand(time(NULL));
     diceRoll = (rand() %6) +1;
     printf("%d\n", diceRoll);
     }

I know how to call it in the main function ( showDice(0); ) and that prints it out. But I need to know how to get it as an int (or another variable) so that I can add it to a total (or counter) variable.

Thanks

  • 4
    Since it's homework I won't do it for you, but your function needs to return something. That should point you in the right direction – dmeglio Oct 10 '15 at 04:15
  • The other alternative is to pass a pointer to `num` so that its value at the original address is updated. (i.e. `void showDice (int *num);`) Then at the end of the function `*num = diceRoll;`. You will then have the value of `diceRoll` in `num` back in `main()`. – David C. Rankin Oct 10 '15 at 04:19
  • 1
    [srand() — why call it only once](http://stackoverflow.com/q/7343833/995714) – phuclv Oct 10 '15 at 04:46

3 Answers3

1

You could simply return it. Something like,

int showDice (int num) {
     int diceRoll;
     srand(time(NULL));
     diceRoll = (rand() % 6) + 1;
     printf("%d\n", diceRoll);
     return diceRoll;
}

Also, if you intended for num to be the number of sides,

int showDice (int num) {
     int diceRoll;
     srand(time(NULL));
     diceRoll = (rand() % num) + 1;
     printf("%d\n", diceRoll);
     return diceRoll;
}

Finally, you should only call srand once (at program startup).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You can just return it (instead of printing it):

int rollDice(int num) {
     int diceRoll;
     srand(time(NULL));
     diceRoll = (rand() %6) +1;
     return diceRoll;
}

Removing some of the extraneous stuff, and if num is the number of sides:

int rollDice(int num) {
     srand(time(NULL));
     return (rand() % num) + 1;
}
ronalchn
  • 12,225
  • 10
  • 51
  • 61
0

What you can do is change the type of the function to an int so that you can return a value, and simply return diceRoll at the end of the function:

int showDice(int num) {
 int diceRoll;
 diceRoll = (rand() %6) +1;
 printf("%d\n", diceRoll);
 return (diceRoll);
}

Then you can call your function like this (note that srand should be called only once):

int main() {
 int rollDice;
 srand(time(NULL));
 rollDice = showDice(0);
}
Guillaume
  • 449
  • 3
  • 14