循环
while
循环判断输入的正整数是几位数
#include <stdio.h>
main()
{
int x = 0;
int n = 1;
printf("enter one numbers:");
scanf("%d",&x);
x /= 10;
while(x > 0)
{
n++;
x /= 10;
}
printf("输入的是%d位数\n",n);
return 0;
}
do while
先执行后判断
int n = 0;
do{
n++;
x /= 10;
} while ( x > 0 );
for
计算阶乘
#include <stdio.h>
main()
{
int n = 3;
int fact = 1;
int i = 1;
for ( i=1; i<=n; i++ ){
fact *= i;
}
printf("%d的阶乘为%d\n",n,fact);
return 0;
}
循环控制
break; 直接跳出循环
continue; 结束本次循环进入下一轮循环
goto out;
…
out:
在多层循环时使用goto跳出所有循环比较方便
练习
整数求逆
注意求逆后首位带不带0的区别
#include <stdio.h>
main()
{
int num = 1100;
int i = 1;
int j = 1;
int new_num = 0;
while (num >= 1){
j = num%10;
printf("%d",j);
//new_num = new_num*10 + j;
num /= 10;
}
printf("\n");
//printf("%d\n",new_num);
return 0;
}
最大公约数
辗转相除法
#include <stdio.h>
main()
{
int t;
int a = 12;
int b = 20;
while (b != 0)
{
t = a%b;
a = b;
b = t;
}
printf("最大公约数为%d\n",a);
return 0;
}
博客主要介绍了循环相关知识,包括while、do while、for循环的应用,如判断正整数位数、计算阶乘等。还讲解了循环控制,如break、continue、goto的使用。最后给出整数求逆、求最大公约数等练习,并提醒求逆时首位带0的区别。
362

被折叠的 条评论
为什么被折叠?



