2020/5/9 for语句

2020-05-09  本文已影响0人  黄灯浸茶
循环中较为复杂的类型:

1.未知次数循环: 一般用while来测试表达式的次数

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语句计算:

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);

练习

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语句

上一篇 下一篇

猜你喜欢

热点阅读