Challenge #2 - my solution

0 Seven Vinton · July 1, 2015
Being new to programming I don't know if there would be a quicker way to solve this challenge, but here is what I came up with:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>

int main()
{
int diceroll1, diceroll2, diceroll3, diceroll4, diceroll5, diceroll6;
int roll_total1, roll_total2;
char roll_compare;
char answer1;
char answer2;
answer2='y';

while(answer2=='y'){

printf("enter 'y' to roll the dice \n");
scanf(" %c", &answer2);

diceroll1 = ( rand()%6) + 1;
printf("%d \n", diceroll1);

diceroll2 = ( rand()%6) + 1;
printf("%d \n", diceroll2);

diceroll3 = ( rand()%6) + 1;
printf("%d \n", diceroll3);

roll_total1 = (diceroll1 + diceroll2 + diceroll3);
printf("Your first roll total score is %d \n", roll_total1);

printf("Will your next roll be high 'H', lower 'L', or even 'E'?");
scanf(" %c", &answer1);
answer1 = tolower(answer1);

diceroll4 = ( rand()%6) + 1;
printf("%d \n", diceroll4);

diceroll5 = ( rand()%6) + 1;
printf("%d \n", diceroll5);

diceroll6 = ( rand()%6) + 1;
printf("%d \n", diceroll6);

roll_total2 = (diceroll4 + diceroll5 + diceroll6);
printf("Your second roll total score is %d \n", roll_total2);

if(roll_total1 > roll_total2){
    roll_compare = 'l';
}
if(roll_total1 < roll_total2){
    roll_compare = 'h';
}
if(roll_total1 == roll_total2){
    roll_compare = 'e';
}

if (answer1 == roll_compare){
    printf("You are a champion! \n");
}
else{
    printf("You Lose! \n");
}
printf("Would you like another roll?\n");
scanf(" %c",&answer2);
}

return 0;
}


It seems to work ok, but it doesn't appear to be very 'random' as it gives the same predictable results each time you run the program.

Post a Reply

Replies

Oldest  Newest  Rating
0 Shreya Kashyap · July 4, 2015
Thanks KD :D that really helped :)
 
0 Seven Vinton · July 2, 2015
That fixed it. Thanks for the advice KD, Cheers.
0 K D · July 2, 2015
that would be because you never seeded the random number generator... import "time.h" and then add at the beginning of the main:
srand(time(NULL));
  • 1

C

107,313 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator