函数程序设计求数列的和

| November 27, 2007 19:09 | timmy | Via Original
编写一个程序,计算数列1+(1+2)+(1+2+3)+…+(1+2+3+…+n)的前n项之和。要求:定义一个含静态局部变量的函数,用于计算数列第i项的值。
例:(括号内为说明)
输入
5(n=5)
输出
sum=35




#include <stdio.h>
long num(int n);
void main()
{
  int n,i;
  long sum=0;

  scanf("%d",&n);
  for(i=1;i<=n;i++)
    sum+=num(i);
  printf("sum=%ld\n",sum);
}
long num(int n)
{
  static long s;
  s+=n;
  return s;
}
Tags:
Program/Code » C/C++ | Comments(0) | Trackbacks(0) | Reads(201)
Add a comment
 Site URI
 Email
  Password Optional
 Nickname  *  [Register]
               

 
Emots
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
Enable HTML
Enable UBB
Enable Emots
Hidden
Remember