c语⾔中continue语句
c语⾔中continue语句;执⾏continue语句后,循环体的剩余部分就会被跳过。
例⼦;
1、原始程序。输出矩形。
#include <stdio.h>
int main(void)
{
int i, j, height, width;
puts("please input the height and width.");
do
{
printf("height = "); scanf("%d", &height);
if (height <= 0)
puts("the range of height is > 0 ");
printf("width = "); scanf("%d", &width);
if (width <= 0)
puts("the range of width is > 0 ");
}
while (height <= 0 || width <= 0);
for (i = 1; i <= height; i++)
{
for (j = 1; j <= width; j++)
{
putchar('*');
}
putchar('\n');
}
return0;
}
当height和width都⼤于0时,程序正常输出矩形。
当height <= 0时,此时程序已经满⾜do语句重新执⾏的条件,但是任然执⾏width的输⼊,因此需要改进。以下使⽤break改进。
2、使⽤break
#include <stdio.h>
int main(void)
{
int i, j, height, width;
puts("please input the height and width.");
do
{
printf("height = "); scanf("%d", &height);
if (height <= 0)
{
puts("the range of height is > 0 ");
break;
}
printf("width = "); scanf("%d", &width);
if (width <= 0)
puts("the range of width is > 0 ");
}
while (height <= 0 || width <= 0);
for (i = 1; i <= height; i++)
{
for (j = 1; j <= width; j++)
{
putchar('*');
}
putchar('\n');
}
return0;
}
当height和width都⼤于0时程序正常执⾏,但是当height⼩于等于0时,程序就直接退出了。以下使⽤continue语句改进。
3、使⽤continue
#include <stdio.h>
int main(void)
{
int i, j, height, width;
puts("please input the height and width.");
do
{
printf("height = "); scanf("%d", &height);
if (height <= 0)
{
puts("the range of height is > 0 ");truncated c语言
continue;
}
printf("width = "); scanf("%d", &width);
if (width <= 0)
puts("the range of width is > 0");
}
while (height <= 0 || width <= 0);
for (i = 1; i <= height; i++)
{
for (j = 1; j <= width; j++)
{
putchar('*');
}
putchar('\n');
}
return0;
}
当height⼩于等于0时,程序会跳过循环体的剩余部分。
执⾏continue语句后,循环体的剩余部分就会被跳过。
例⼦:
#include <stdio.h>
int main(void)
{
int i, j;
puts("please input an integer.");
printf("j = "); scanf("%d", &j);
for (i = 1; i <= j; i++)
{
if (i == 6)
break;
printf("%d ", i);
}
putchar('\n');
puts("xxxxxyyyyyy");
return0;
}
break语句会直接终⽌循环。
下⾯看continue。
#include <stdio.h>
int main(void)
{
int i, j;
puts("please input an integer.");
printf("j = "); scanf("%d", &j);
for (i = 1; i <= j; i++)
{
if (i == 6)
continue;
printf("%d ", i);
}
putchar('\n');
puts("xxxxxyyyyyy");
return0;
}
continue语句则是仅仅跳出“6”的那⼀次执⾏过程。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。