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?
#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);
}
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
Such as?
Quote from: mrprime on May 25, 2013, 09:56:11 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
Quote from: Bitbeisser on May 25, 2013, 10:43:56 PM
- 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 (http://www.codingunit.com/c-reference-stdlib-h-function-rand-generate-a-random-number):
The function rand() returns a pseudo-random integral number.
This number will be in the range 0 to RAND_MAX.