循环中较为复杂的类型:
1.未知次数循环: 一般用while来测试表达式的次数
- 一行字符分类统计
- 一行以0结尾的整数,求平均数
- Pi/4 =1 - 1/3 + 1/5 - 1/7 + ....
- e = 1 + 1/1! + 1/2! + 1/3! + ....
Example:(泰勒级数展开式)
sinx = x- x^3/3! + x^5/5! - x^7/7! + .......+ 0
#define PI = 3.1415926
double x,sum,term;
int k,s;
scanf("%Ld", &x);
//第一项,递推起点 x/1
term = x;
k = 1;
s = 1;
while( term * >1e-6 )
{
sum += term *s;
s = -s;
k = k+2;
term = term *x*x/((k-1)*k);
}
printf("%.2f", sum);
for语句
一般用于 已知次数的循环
1.设置循环变量进行记数
2.使用for语句
用for语句计算:
- 1 + 2! + 3! + ...... +n!
int s, n, t;
int i;
scanf("%d", &n);
t = 1;
s = t; | i=2;
for(i=2;i<=n;i++) | for(;i<=n;i++)
{ |
t =t * i; |
s += t; | i++ 或者放在循环末尾
} |
printf("%d", s);
当在for语句后直接加分号
下例子输出为:6
int s=0;
int n=5;
int i;
for( i=1;i<=n;i++);
s+=i;
printf("%d\n", s);
练习
- a + aa + aaa + ... + n个a
int s,a,n,i,t;
t=0;
s=0;
scanf("%d%d", &a,&n);
for(i=1;i<=n;i++)
{
t = t*10 + a;
s += t;
}
printf("sum is :%d",s);
return 0;
- 水仙花数
//水仙花数 abc = a^3 + b^3 + c^3
int n,a,b,c;
//for用来遍历100-999的数
for(n=100;n<=999;n++)
{
//----该模块负责判断是否为水仙花数---------
c = n%10; //个位数
b = n/10%10; //十位数
a = n/100; //百位数
if(n == a*a*a + b*b*b + c*c*c)//判断各个位的立方数是否等于n
{
printf("%d\n", n);
}
}
=======================
总结 :循环的编程模式
1.递推
2.穷举
已知次数循环for语句
未知次数循环while语句
网友评论