1.代码示例
问题:如何一达到了输出printf的条件就跳出整个循环?
#include<stdio.h>
int main()
{
int x;
int one,two,five;
scanf_s("%d", &x);
for (one = 1; one < x * 10; one++)
{
for (two = 1; two < (x * 10) / 2; two++)
{
for (five = 1; five < (x * 10) / 5; five++)
{
if (one + two * 2 + five * 5 == x * 10)
{
printf("可以用%d个一角加%d个二角加%d个五角得到%d元\n", one, two, five,x);
break;
}
}
}
}
}
以上的代码,加break只能跳出它所在的那一层循环,无法实现,所以要引出两个能在多层嵌套循环里用的跳出语句
2.接力break与goto语句
接力break代码
#include<stdio.h>
int main()
{
int exit;
int x;
int one,two,five;
scanf_s("%d", &x);
for (one = 1; one < x * 10; one++)
{
for (two = 1; two < (x * 10) / 2; two++)
{
for (five = 1; five < (x * 10) / 5; five++)
{
if (one + two * 2 + five * 5 == x * 10)
{
printf("可以用%d个一角加%d个二角加%d个五角得到%d元\n", one, two, five,x);
exit = 1;
break;
}
}
if (exit == 1)
break;
}
if (exit == 1)
break;
}
}
goto 语句代码示例
#include<stdio.h>
int main()
{
int x;
int one,two,five;
scanf_s("%d", &x);
for (one = 1; one < x * 10; one++)
{
for (two = 1; two < (x * 10) / 2; two++)
{
for (five = 1; five < (x * 10) / 5; five++)
{
if (one + two * 2 + five * 5 == x * 10)
{
printf("可以用%d个一角加%d个二角加%d个五角得到%d元\n", one, two, five, x); \
goto out;
}
}
}
}
out:
return 0;
}
tips
1.goto语句强制中断本语句后面的语句,适用范围仅限于一个函数内部不可以跳转到其他函数内。
2.goto语句可以一次跳出许多层循环
3.可以对for循环中包含的if条件句加一个goto,方便我们对满足条件的部分进行及时的处理。
goto语句 语法
设置一个后面带冒号的标签,标签的名字可以任意去取,冒号后面的是想要对语句进行的操作。