我正在在线学习用 c 语言编写代码,并尝试在该程序中使用 do while 循环
这是一个骰子游戏程序
玩家最低金额1000
即可进入游戏。
玩家可以尝试任意次数的机会。如果骰子
的值为1
,则玩家离开游戏时将获得一半的金额。
如果数值不是1
,则总金额按骰子
的100*value
倍数增加。
如果玩家退出,他/她将带着他/她所拥有的金额离开游戏。
#include <stdio.h>
#include <stdlib.h>
int main () {
int cash, dice;
char ch;
printf ("cash\n");
scanf ("%d", &cash);
if (cash < 1000) {
printf ("No\n");
exit (0);
}
else {
do {
printf ("dice\n");
scanf ("%d", &dice);
while (dice < 1 || dice > 6) {
printf ("\n invalid");
printf ("dice\n");
scanf ("%d", &dice);
}
if (dice == 1) {
cash = cash / 2;
break;
}
cash = (dice * 100) + cash;
printf ("Do you want to continue");
scanf ("%c", &ch);
} while (ch == 'y');
}
printf ("won=%d", cash);
return 0;
}
此程序不接受 y
或 n
输入。
它显示语句你想继续吗
并直接转到 won 语句。
最佳答案
您的第二个 scanf
正在消耗 dice
留在 stdin
中的 '\n'
字符
只需在格式说明符之前添加一个空格,您就可以在接受用户插入的字符之前消耗 stdin 中的所有字符:
scanf (" %c", &ch);
在 scanf()
格式中,空白、制表符或换行符表示“如果有要跳过的空白,则跳过空白”。
关于c - 在c中使用do while循环来表示yes no提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38865855/