【发布时间】:2019-04-01 11:54:27
【问题描述】:
我正在尝试制作一个 Magic 8 Ball 程序,但我的循环有一个错误。
如果您再次播放,循环就会混乱,并且表现得就像您一直按 Enter 大约三个循环一样,直到它再次工作。
另外,输入问题时会有延迟。你必须按两次回车才能得到答案。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
void ans(int x);
int main()
{
system("color 0A");
srand(time(0));
int num,i;
do{
char question[100] = {" "};
num = rand()%10;
puts("MAGIC 8 BALL!");
puts("Press Enter When Ready.");
getch();
system("cls");
puts("Input Yes or No questions only!");
printf("\n");
scanf("%s",&question);
getch();
printf("\nTHE ANSWER | ");
ans(num);
getch();
system("cls");
printf("Press any key to try again.\nPress [x] to Exit.");
if(getch()=='x'){
system("cls");
break;
}
system("cls");
}while(1);
}
void ans(int x){
switch(x){
case 1 : printf("YES!");break;
case 2 : printf("NO!");break;
case 3 : printf("It's a thumbs down.");break;
case 4 : printf("Positive!");break;
case 5 : printf("As I see it Yes.");break;
case 6 : printf("Certainly!");break;
case 7 : printf("Negative!");break;
case 8 : printf("Don't Count on it.");break;
case 9 : printf("You don't want to know, trust me.");break;
case 10: printf("I can't say right now.");break;
default : printf("Cannot be determined right now");break;
}
}
【问题讨论】:
-
我建议你在主函数中去掉第二个
getch() -
另请注意,
num = rand()%10;为您提供的值是 0 到 9,而不是 1 到 10。您可以调整 switch 语句来处理它。
标签: c function while-loop