C代码,随机骰子游戏没有给出正确答案需要帮助
我正在尝试制作一个游戏,它将3个骰子随机掷出,显示3个骰子的第一个和,然后询问用户下一个骰子的和是更高(h)、更低(l)还是相同(s)。我觉得我很快就能让它工作了,但当我运行游戏时,我似乎无法让用户输入与答案“对齐”(如果这有意义的话) 以下是我目前的代码:C代码,随机骰子游戏没有给出正确答案需要帮助,c,random,dice,C,Random,Dice,我正在尝试制作一个游戏,它将3个骰子随机掷出,显示3个骰子的第一个和,然后询问用户下一个骰子的和是更高(h)、更低(l)还是相同(s)。我觉得我很快就能让它工作了,但当我运行游戏时,我似乎无法让用户输入与答案“对齐”(如果这有意义的话) 以下是我目前的代码: #include<stdio.h> #include<stdlib.h> #include<ctype.h> #include<string.h> #include<math.
#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;
正如你所希望看到的,在游戏继续运行之前,我必须在第一次输入两个输入。在输出的例子中,我猜了几次h(更高),当骰子的总和从8变为9时,我得到了一次正确的结果,但是当我输入l(更低)并且骰子从9变为4时,我得到了“不正确”
您正在读取函数中的单字符,这意味着这永远不会等于true
scanf("%c\n\n",&userInput);
改用fgets
,然后用sscanf将其读入字符
您正在读取函数中的单字符,这意味着这永远不会等于true
scanf("%c\n\n",&userInput);
改用fgets
,然后用sscanf
将其读入一个字符,你说的“排队”是什么意思?请编辑问题,使其包含一些实际输出示例和预期输出?scanf
无法识别新行,但只有在输入新行时才处理输入。这使得输入和输出看起来不同步。更好的方法是先用fgets
读取整行,然后用strtok
或sscanf
扫描整行。您正在读取单个字符,因此您的输入永远不能“退出”
。此外,userinput
的地址将与字符串文本等其他内容的地址不匹配。您需要strcmp
来比较字符串。哦,还有表达式&userInput=“quit”
永远不会为真。大多数逻辑都不正确,请尝试使用gdb进行调试。您所说的“排队”是什么意思?请编辑问题,使其包含一些实际输出示例和预期输出?scanf
无法识别新行,但只有在输入新行时才处理输入。这使得输入和输出看起来不同步。更好的方法是先用fgets
读取整行,然后用strtok
或sscanf
扫描整行。您正在读取单个字符,因此您的输入永远不能“退出”
。此外,userinput
的地址将与字符串文本等其他内容的地址不匹配。您需要strcmp
来比较字符串。哦,还有表达式&userInput=“quit”
永远不会为真。大多数逻辑都不正确,请尝试使用gdb进行调试。
scanf("%c\n\n",&userInput);