以下程序无法正常运行。它应该是一个不应该反复循环的计算游戏。我不确定发生了什么。我尝试重新安排一些事情,但这没有帮助。我注意到,在用户输入数字并回答问题之后,即使它应该显示,它也会转到mainMenu。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//Declaration Statement
double num1;
double num2;
double answer;
int choice;
void pauseProgram()
{
printf("\nPress any key to continue...");
getchar();
}
//Function Title
void title(char * programTitle)
{
int len = strlen(programTitle);
system("cls");
printf("\n");
for(int i=1; i<40 - len/2;i++) printf(" ");
printf("%s\n",programTitle);
}
void intro()
{
title("Calculation Game");
printf("\nThis program will test your math abilites");
pauseProgram();
}
void userInput()
{
title("Calculation Game");
printf("\nPlease enter positive numbers only\n");
printf("Enter a number:");
scanf("%lf",&num1);
getchar();
printf("Enter another number:");
scanf("%lf",&num2);
getchar();
printf("What is %lf + %lf?",num1,num2);
scanf("%lf",&answer);
if (num1<0 or num2<0)
{
printf("\nSorry, you must enter a positive value! Please try again.");
userInput();
pauseProgram();
}
}
void display()
{
title("Calculation Game");
if (answer=num1+num2)
printf("\nWow you got the right answer\n");
else if (answer!=num1+num2)
printf("\nHmmm...maybe we should review this math concept again!\n");
pauseProgram();
}
void goodbye()
{
title("Calculation Game");
printf("\nFor further information call: 1-800-123-4567\n");
pauseProgram();
}
void mainMenu()
{
title("Calculation Game");
printf("\n1.\tPlay Game");
printf("\n2.\tExit\n");
printf("\nEnter 1 or 2:");
scanf("%d",&choice);
getchar();
if (choice==1)
userInput();
if (choice=2)
goodbye();
if (choice!=1 or choice!=2);
{
printf("\nPlease enter either 1 or 2! Please try again.");
mainMenu();
}
}
//Main program
int main()
{
do
{
intro();
mainMenu();
userInput();
if (answer==num1+num2 or answer!=num1+num2)
{
display();
}
}while(1);
goodbye();
}
答案 0 :(得分:0)
正如我在评论中提到的那样,您可能会看到main()
函数进入无限循环:
do {
...
} while (1)
这个循环不会停止,直到被告知。例如,您可以告诉程序退出pauseProgram()
函数:
void pauseProgram()
{
printf("\nPress any key to continue...");
getchar();
exit(0);
}
或在goodbye()
函数中:
void goodbye()
{
title("Calculation Game");
printf("\nGame designed by David Liubart\n");
printf("\nFor further information call: 1-800-123-4567\n");
pauseProgram();
exit(0);
}
最后,您可以在循环中的任何位置使用break
指令以退出循环。