我正在关注 youtube 上的教程并正在制作一个骰子生成器。 它基本上打印出 3 个骰子结果并将骰子结果相加。 之后,用户将查看总和,并根据总和猜测下一卷是更高、更低还是相同。
下面是我的代码,假设,当我输入"is"时,它应该在 if 语句中执行代码。但是,它直接转到了 else 语句。谁能告诉我哪里出了问题?
int answer;
int guess;
int diceRoll4 = 0;
printf("Would you like to guess your next dice? Y/N \n");
scanf(" %c", &answer);
if (answer == 'yes' ){
printf("What is your guess?\n");
printf("please key in your number \n");
scanf(" %d", &guess);
if (guess > diceRoll4 ){
printf(" You got it wrong, too high!");
}
else if (guess < diceRoll4){
printf(" You got it wrong, too low!");
}
else {
printf("You got it right");
}
}
else{
printf("Thanks for playing");
}
最佳答案
首先,answer
应该是一个 char
数组,以便保存一个字符串。改变
int answer;
到
char answer[10]; //Or any other reasonable size
其次,既然你想扫描一个字符串而不是一个字符,改变
scanf(" %c", &answer);
到
scanf("%9s", answer);
9 将扫描最多 9 个字符(末尾的 NUL 终止符 +1),从而防止 buffer overflows .
我删除了 &
,因为 %s
需要一个 char*
而 &answer
会给出一个 char( *)[10]
。数组的名称被转换为指向其第一个元素 char*
的指针,这正是 %s
所期望的。上面的 scanf
等价于
scanf("%9s", &answer[0]);
第三,使用 ==
比较两个字符串比较的是指针而不是其中的实际内容。请改用 string.h
中的 strcmp
。当它的两个参数都包含相同的内容时,它返回 0。改变
if (answer == 'yes' ){
到
if (strcmp(answer, "yes") == 0){
双引号用于表示以 NUL 结尾的字符串 (char*
),这正是 strcmp
所期望的,而在您的代码中,单引号是一个多字 rune 字,其值是实现定义的。
关于c - 生成骰子游戏 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827118/