[英]C Code, Help Needed with Randomized dice game not giving correct answer
我正在尝试制作一个随机分配3个骰子骰子的游戏,显示3个骰子的第一个总和,然后询问用户他们是否认为下一骰子的总和将更高(h),更低(l)或相同( S)。 我觉得我已经接近要运行它了,但是当我运行游戏时,我似乎无法获得用户输入,使它与答案应该是“对等的”(如果这样的话。)。
到目前为止,这是我的代码:
#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;
}
运行此代码的输出如下:
***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
如您所愿,我必须在游戏继续运行之前的第一次输入两个输入。 在输出示例中,当骰子的总和从8变为9时,我猜了几次h(high)并使其一次正确,但是当我输入l(lower)并且骰子从9变为4时,我得到“不正确”。
while(&userInput!="quit" ){
您正在读取函数中的单个字符,这意味着这将永远不等于true。
scanf("%c\n\n",&userInput);
改用fgets
,然后用sscanf
将其读入char
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.