-1

(C code) Each die has its own function, and I want a function that will sum the outcome of each die. But how do I retrieve the values from the first and second functions and put them into the third to sum them? See below

int roll_die1(void)
{
    int random_int;
        srand((unsigned int)time(NULL));
        random_int = rand() % (6) + 1;
        printf("The outcome of your first Roll is: %d.\n", random_int);

    return random_int;
}

int roll_die2(void)
{
        int random_int2;
        srand((unsigned int)time(NULL));
        random_int2 = rand() % (6) + 1;
        printf("The outcome of your second Roll is: %d.\n", random_int2);

    return random_int2;

}

int calculate_sum_dice(int die1_value, int die2_value)
{
   int sum = die1_value + die2_value;
   return sum;
}

Now I can't just call the first two functions into the 3rd function, because it would repeat all the steps in those functions, so how do I do it?

Edit: In my main.c, to get the sum I did

roll1 = roll_die1();
roll2 = roll_die2();
sum = calculate_sum_dice(roll1, roll2);
user43783
  • 145
  • 6
  • There is nothing wrong with your code. It works as expected. – alvits Feb 25 '17 at 04:04
  • There's something very wrong with your code — see [`srand()`: why call it just once?](http://stackoverflow.com/questions/7343833/srand-why-call-it-only-once/) – Jonathan Leffler Feb 25 '17 at 04:07
  • Note that you don't need two functions to do the same calculation twice. You use different functions to do different jobs. Also, if you're very careful, you'll find there's a bias towards the lower numbers (against sixes), unless `RAND_MAX + 1` on your machine is divisible by 6, which would be very unusual. – Jonathan Leffler Feb 25 '17 at 04:09

1 Answers1

2

Just allow calculate_sum_dice() to retrieve both results from roll_die1() and roll_die2() and return the sum. Their is no need to include any function parameters for calculate_sum_dice(). You can also just call srand() once in main(), as it just sets a seed for rand(), so it would be pointless to call it more than once. Have a look at srand(): why call it just once?, as pointed out by @Jonathan Leffler in the comments.

Here is what your code should look like:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int roll_die1(void) {
    int random_int;
    random_int = rand() % (6) + 1;
    printf("The outcome of your first Roll is: %d.\n", random_int);

    return random_int;
}

int roll_die2(void) {
    int random_int2;
    random_int2 = rand() % (6) + 1;
    printf("The outcome of your second Roll is: %d.\n", random_int2);

    return random_int2;

}

int calculate_sum_dice(void) {
   int sum = roll_die1() + roll_die2();
   return sum;
}

int main(void) {
    srand((unsigned int)time(NULL));

    int sum = calculate_sum_dice();

    printf("Dice sum = %d\n", sum);

    return 0;
}
Community
  • 1
  • 1
RoadRunner
  • 25,803
  • 6
  • 42
  • 75