# Challenge 2 Problem

0 Laur T · August 25, 2015
Ok so I finished my program and I noticed that my three dice are rolling the same values and I wonder why?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

int main()
{
    int i,sum,sum2,diceRoll1,diceRoll2,diceRoll3;
    char x;
    diceRoll1=(rand()%6)+1;
    diceRoll2=(rand()%6)+1;
    diceRoll3=(rand()%6)+1;
    sum=diceRoll1+diceRoll2+diceRoll3;
    printf("%d %d %d\n",diceRoll1,diceRoll2,diceRoll3);
    printf("The sum is : %d\n",sum);
    printf("Is gonna be higher ,lower or the same (h,l,s): ");
    scanf(" %c",&x);
    switch(x)
{
    case 'h':
        diceRoll1=(rand()%6)+1;
        diceRoll2=(rand()%6)+1;
        diceRoll3=(rand()%6)+1;
        sum2=diceRoll1+diceRoll2+diceRoll3;
        printf("%d %d %d\n",diceRoll1,diceRoll2,diceRoll3);
        printf("The sum is : %d\n",sum2);
    if(sum2>sum)
        printf("Good job the sum is higher!");
    else
        printf("The sum is not higher!");
        break;
    case 'l':
        diceRoll1=(rand()%6)+1;
        diceRoll2=(rand()%6)+1;
        diceRoll3=(rand()%6)+1;
        sum2=diceRoll1+diceRoll2+diceRoll3;
        printf("%d %d %d\n",diceRoll1,diceRoll2,diceRoll3);
        printf("The sum is : %d\n",sum2);
    if(sum2<sum)
        printf("Good job the sum is lower!");
    else
        printf("The sum is not lower!");
        break;
    case 's':
        diceRoll1=(rand()%6)+1;
        diceRoll2=(rand()%6)+1;
        diceRoll3=(rand()%6)+1;
        sum2=diceRoll1+diceRoll2+diceRoll3;
        printf("%d %d %d\n",diceRoll1,diceRoll2,diceRoll3);
        printf("The sum is : %d\n",sum2);
    if(sum2==sum)
        printf("Good job the sum is the same!");
    else
        printf("The sum is not the same!");
        break;
    default:printf("Invalid key!");
}
return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 c student · August 25, 2015
rand uses a mathematical expression to calculate the numbers. using srand (seed) provides an alteration to this calculation. if your seed is static (the same every time), so will your rand value. if your seed is dynamic (constantly changing), so will your rand value.
a typical srand is:

#include <time.h>

srand (time (NULL));

note that you will only need to call srand once.
0 Laur T · August 26, 2015
Ok thanks for the info
  • 1

C

107,111 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator