I am trying to make a game which randomizes 3 dice rolls, displays the first sum of the 3 dice and then asks the user if they think the sum of the next roll will be higher(h), lower(l) or the same(s). I feel I am close to having it working but when I run the game, I cant seem to get the user input to "line up" with what the answer should be (if that makes sense..).
Here is my code so far:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<math.h>
#include<time.h>
int main(){
srand(time(NULL));
char userInput;
int diceOne=(rand()%6)+1;
int diceTwo=(rand()%6)+1;
int diceThree=(rand()%6)+1;
int firstRoll = diceOne+diceTwo+diceThree;
int prevSum,newSum;
printf("***Welcome to the dice guessing game!***\n\n");
printf("Rules:\n type 'quit' to exit game\n'h' for higher\n'l' for lower\n's' for same.\n\n");
printf("dice one: %d\ndice two: %d\ndice three: %d\n",diceOne, diceTwo, diceThree);
printf("The starting total is: %d\n",firstRoll);
while(&userInput!="quit" ){
void randDice (void){
diceOne=(rand()%6)+1;
diceTwo=(rand()%6)+1;
diceThree=(rand()%6)+1;
}
printf("Guess:");
scanf("%c\n\n",&userInput);
prevSum = diceOne+diceTwo+diceThree;
randDice();
newSum = diceOne+diceTwo+diceThree;
if((userInput=='h') && (prevSum > newSum)){
printf("Correct!\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
} else if((userInput=='l') && (prevSum < newSum)){
printf("Correct!\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
} else if((userInput=='s') && (prevSum == newSum)){
printf("Correct!\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
} else {
printf("Incorrect\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
}
}
return 0;
}
The output from running this code is as follows:
***Welcome to the dice guessing game!***
Rules:
type 'quit' to exit game
'h' for higher
'l' for lower
's' for same.
dice one: 3
dice two: 4
dice three: 1
The starting total is: 8
Guess:h
h
Incorrect
The sum of the three dice was: 8
Guess:h
Incorrect
The sum of the three dice was: 8
Guess:h
Correct!
The sum of the three dice was: 9
Guess:l
Incorrect
The sum of the three dice was: 4
As you can hopefully see, I have to enter two inputs the first time before the game will continue to run. In the example of the output I guessed h(higher) a few times and got it correct once when the sum of the dice changes form 8 to 9, but when I enter l(lower) and the dice change from 9 to 4, I get "incorrect".
while(&userInput!="quit" ){
You are reading single chars in your function, which means this will never equal true.
scanf("%c\n\n",&userInput);
Use fgets
instead and then read that into a char with sscanf
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.