while语句
1.while使用
打印1-10
#include<stdio.h>
int main()
{
int a = 1;
while (10 >= a)
{
printf("%d\n", a);
a += 1;
}
return 0;
}
2.while语句中的break,continue
break:
跳出while语句
#include<stdio.h>
int main()
{
int a = 0;
while (a <= 10)
{
if (5 == a)
break;
a++;
printf("%d\n", a);
}
return 0;
}
continue:
跳过本次循环中continue后边代码,继续进行下一次循环的判断
#include<stdio.h>
int main()
{
int a = 0;
while (a <= 10)
{
if (5 == a)
continue;
a++;
}
return 0;
}
无法执行最后一步,死循环
3.练习
1.连续输入字符,只打印数字字符,其他字符直接跳过不做处理
#include<stdio.h>
int main()
{
char ch = 0;
while((ch=getchar())!=EOF)
{
if (ch < '0' || ch>'9')
continue;
else
putchar(ch);
}
return 0;
}
2.输入一个正整数,逆序打印这个数的每一位
#include<stdio.h>
int main()
{
int a = 0;
int b = 0;
scanf("%d", &a);
while (a != 0)
{
b = a % 10;
printf("%d", b);
a = a / 10;
}
return 0;
}
简洁版
#include<stdio.h>
int main()
{
int a = 0;
scanf("%d", &a);
while (a)
{
printf("%d", a % 10);
a /= 10;
}
return 0;
}