如何摆脱 C 中的嵌套循环?
How to get out of nested loops in C?
我想退出 C 中的嵌套 while 以返回主函数。但我不知道该怎么做。我的意思是,在我的代码中,我想使用一条指令(goto 指令除外,因为我想制作一个程序程序)来打破这两个循环并返回到主函数。
这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main()
{
float *Score = (float*) malloc (5 * sizeof (float));
if (!Score)
{
printf("An error occurred while allocating memory.\n");
exit(1);
}
char *Character = (char*) malloc (sizeof (char));
if (!Character)
{
printf("An error occurred while allocating memory.\n");
exit(2);
}
int Counter = 0;
while (Counter < 5)
{
printf("Enter your number %d : ", Counter + 1);
scanf("%f", (Score + Counter));
system("cls");
if (Counter == 5 - 1)
{
break;
}
while (1)
{
printf("Do you want to continue? ");
*Character = getch();
system("cls");
if (*Character == 'y')
break;
else if (*Character == 'n'); // I don't know what do I do here?
else
{
printf("Press enter \'y\' or \'n\'\n");
continue;
}
}
Counter++;
}
Counter = 0;
while (Counter < 5)
{
printf("%2.2f - ", *(Score + Counter));
Counter++;
}
getch();
return 0;
}
我想制作程序程序,因此我不能使用goto指令。有人可以帮助我吗?
首先,在嵌套的 while 循环的那个条件中添加一个 break 语句:
else if (*Character == 'n')
break;
然后,在嵌套的 while 循环结束后,在封闭的 while 循环中添加相同的条件以跳出它并返回到主函数:
if (*Character == 'n')
break;
如果在嵌套循环中声明了 Character
,它将不会起作用。
或者(更好的方法),在您的情况下,您还可以在嵌套 while 循环中的该条件内设置封闭 while 循环的终止条件,然后再跳出它。这将确保封闭的循环不会进一步迭代:
else if (*Character == 'n')
{
Counter = 5; // condition of the enclosed while-loop becomes false
break; // breaks out of the nested while-loop
// altogether, you break out of both the loops
}
我想退出 C 中的嵌套 while 以返回主函数。但我不知道该怎么做。我的意思是,在我的代码中,我想使用一条指令(goto 指令除外,因为我想制作一个程序程序)来打破这两个循环并返回到主函数。
这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main()
{
float *Score = (float*) malloc (5 * sizeof (float));
if (!Score)
{
printf("An error occurred while allocating memory.\n");
exit(1);
}
char *Character = (char*) malloc (sizeof (char));
if (!Character)
{
printf("An error occurred while allocating memory.\n");
exit(2);
}
int Counter = 0;
while (Counter < 5)
{
printf("Enter your number %d : ", Counter + 1);
scanf("%f", (Score + Counter));
system("cls");
if (Counter == 5 - 1)
{
break;
}
while (1)
{
printf("Do you want to continue? ");
*Character = getch();
system("cls");
if (*Character == 'y')
break;
else if (*Character == 'n'); // I don't know what do I do here?
else
{
printf("Press enter \'y\' or \'n\'\n");
continue;
}
}
Counter++;
}
Counter = 0;
while (Counter < 5)
{
printf("%2.2f - ", *(Score + Counter));
Counter++;
}
getch();
return 0;
}
我想制作程序程序,因此我不能使用goto指令。有人可以帮助我吗?
首先,在嵌套的 while 循环的那个条件中添加一个 break 语句:
else if (*Character == 'n')
break;
然后,在嵌套的 while 循环结束后,在封闭的 while 循环中添加相同的条件以跳出它并返回到主函数:
if (*Character == 'n')
break;
如果在嵌套循环中声明了 Character
,它将不会起作用。
或者(更好的方法),在您的情况下,您还可以在嵌套 while 循环中的该条件内设置封闭 while 循环的终止条件,然后再跳出它。这将确保封闭的循环不会进一步迭代:
else if (*Character == 'n')
{
Counter = 5; // condition of the enclosed while-loop becomes false
break; // breaks out of the nested while-loop
// altogether, you break out of both the loops
}