因此,在此链接->执行while循环问题时,我遇到了一个问题,该问题涉及使用while
代替而非调用的问题main()
,这对我有帮助,我的代码可以正常工作,但是有一个新的小问题。我会用一种“骰子滚子代码”来展示它
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
srand((unsigned)time(NULL));
int totalSides, dice, modifier;
char c, d;
printf("Welcome to the dice roller!\n");
printf("If you wanna roll the dice, press 'r'. If you wanna quit, press 'q': ");
scanf(" %c", &c);
while(c == 'r'){
printf("How many sides does the dice you want to roll have? Answer with a int number: ");
scanf("%d", &totalSides);
printf("Do you need any modifier? Press 'a' to add, press any other key to dispense: ");
scanf(" %c", &d);
if(d == 'a'){
printf("Insert your modifier value: ");
scanf("%d", &modifier);
printf("\n");
}
dice = rand() % totalSides + 1;
printf("You've got a %d!\n", dice);
if(d == 'a'){
printf("But you've got a %d modifier...\n", modifier);
dice = dice + modifier;
printf("Then, you got a %d!", dice);
}
printf("\n\n\n\n");
repeat();
c = repeat();
printf("\n\n\n\n");
}
}
int repeat(){
char c;
printf("Do you want to reroll? Press 'r' to reroll, pres 'q' to quit: ");
scanf("%c", &c);
return c;
}
该程序运行良好,但是在输出中我得到了两次相同的句子,例如:“您要重新滚动吗?按'r'重新滚动,按'q'退出:是否要重新滚动?按'r '重新滚动,按'q'退出:“
我该如何解决?
您正在拨打repeat
两次,因此它正在打印两次。
repeat();
c = repeat();
尝试替换第一个通话以重复到getchar()
。这将消耗在修饰符行之后输入的字符。
getchar();
c = repeat();
看来您刚刚开始学习C,可能值得读一本书。一,我可以推荐是的Modern C。它可以免费在线获得,也可以购买印刷版。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句