【发布时间】:2020-06-04 16:52:55
【问题描述】:
我正在学习诸如 for 和 while 循环之类的循环,因此我决定自己进行测试并编写一个程序,您可以在下面看到代码。该程序为用户提供了一系列选项来输入选项,但我遇到的问题是我希望能够在操作完成后不断要求用户“输入命令”。
例如,如果我输入 1,则将执行必要的代码,但整个程序就结束了。如何增强此程序,使其不断要求用户输入新命令,直到用户输入 0 强制退出?
#include <stdio.h>
int main()
{
int n;
int credit = 0;
int YN;
printf("Welcome to Cash booking software Version 2.145\n");
printf("--------------------------------------------------------\n");
printf("Use the following options:\n");
printf("0 -- Exit\n");
printf("1 -- Display Credit\n");
printf("2 -- Change Credit\n");
printf("3 -- Remove Credit\n");
printf("\n");
for ( ; ; )
{
printf("Enter a command: ");
scanf("%d", &n);
if (n == 0)
{
return 0;
}
else if (n == 1)
{
printf("Your credit is £%d", credit);
}
else if (n == 2)
{
printf("Enter a new credit value: \n");
scanf("%d", &credit);
printf("Your new credit value is %d", credit);
}
else if (n == 3)
{
printf("Are you sure you want to remove your Credit value? (Y=1/N=2)");
scanf("%d", &YN);
if (YN == 1)
{
credit = 0;
}
else
;
}
return 0;
}
}
【问题讨论】:
-
由于您仍然熟悉该语言,我强烈建议习惯使用它的一些最常用的工具:对于这种情况,它是调试器。如果您在终端中运行程序,则可以使用 gdb。如果您使用的是 IDE,例如 VS Code,它们通常集成了调试器。使用调试器,您将能够一步一步地看到程序在做什么。
-
我认为你的情况很好,错误可能是
return 0;应该在 for 循环之外的}之后(即像你想要的那样无限循环)。所以把 return 放在最后一个}之前应该没问题。 -
当代码格式整齐时,最终
return 0;在for循环内而不是在它之后的错误变得明显。将其移出循环,您的循环将继续。 -
最好使用调试器或正确格式化代码,但不像初学者那么容易,所以我们必须让他犯一些错误:) 并花一些时间在上面。就像我们每个人一样! :)
-
谢谢大家的帮助!!!!!!