NO

Author Topic: Die Roller problem.  (Read 3281 times)

mrprime

  • Guest
Die Roller problem.
« on: May 24, 2013, 11:16:37 PM »
Alright, this has been driving me batty for a while now. I've been trying to make a simple die-rolling game for sometime now, I think I have the If Else statements down pat but it isn't reading correctly...

Help?

Code: [Select]
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main(void) {
int ans;
int i;

printf("Care to play a game? The rules are simple: Two 20-sided die is rolled.\n");
printf("If your die rolls 1, you lose.\n");
printf("But if yours rolls 20, you win.\n");
printf("Anything between? Re-roll!\n");
printf("You may only re-roll ten times!\n");

srand(time(NULL));
for (i = 1; i <= 20; i++) {

printf("The Die rolled a %d.\n", (rand() % 20));

if ( rand() > 20 && rand() < 2 ) {
printf("Re-roll? (Y/N)?");
  scanf("%d", &ans);

while (ans == 'Y' || ans == 'y');
   }
else if (rand() == 1 )
{
printf("You rolled a 1. YOU LOSE!\n");

return(0);
}
else ( rand() == 20);{
printf("You rolled 20!! YOU WIN!\n");
}

}
return(0);
}
« Last Edit: May 25, 2013, 01:13:53 AM by Bitbeisser »

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: Die Roller problem.
« Reply #1 on: May 25, 2013, 01:15:29 AM »
Well, the most obvious problem is the way how you use the rand() function. You don't take into account that each call to the function will give a different result!  ;)

And there are a plethora of other, logical errors along the way as well...

Ralf
« Last Edit: May 25, 2013, 01:21:56 AM by Bitbeisser »

mrprime

  • Guest
Re: Die Roller problem.
« Reply #2 on: May 25, 2013, 09:56:11 PM »
Such as?

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: Die Roller problem.
« Reply #3 on: May 25, 2013, 10:43:56 PM »
Such as?
Well,

- you state that the intention is to roll the dice up to ten times if there is no win or loss, but you run the for loop 20 times...

- the first if() is never true ( >20 and <2), so you will never re-roll a dice

- the while () loop runs forever, as you did not properly scope/bracketed what is actually to be repeated

I usually don't like to do this, as we don't provided finished homework assignments, but a working project file is attached


Ralf

Offline jj2007

  • Member
  • *
  • Posts: 536
Re: Die Roller problem.
« Reply #4 on: May 26, 2013, 01:08:00 AM »
- the first if() is never true ( >20 and <2), so you will never re-roll a dice

Almost never ;-)

@mrprime: You should study the rand() documentation, e.g. here:
The function rand() returns a pseudo-random integral number.
This number will be in the range 0 to RAND_MAX.