编程求:S=-(2! / 1!) + [4! / (1! - 3!)] - [6! / (1! - 3! + 5!)] + [8! / (1! - 3! + 5! -7!)] -……。项数N的值由键盘输入,且1<=N<=20.
代码:#include<iostream>
using namespace std;
int main()
{
int n,i,j,m,k=1,p=0;
long int l=1;
cout<<"请输入数目:";
cin>>n;
cout<<endl;
long int a[n],b[n],c[n];
c[1]=2;
cout<<"生成的奇数项数目:" ;
for(m=1;m<=n;m++)
{
l=1;
for(j=1;j<=2*m-1;j++)
l*=j; //求2n-1的阶乘
a[m]=l; //存放阶乘结果
cout<<a[m]<<" ";
}
cout<<endl;
for(m=1;m<=n;m++)
{
if(m%2==0)
a[m]=-a[m]; //改变奇偶项的符号
cout<<a[m]<<" ";
}
cout<<endl;
b[1]=a[1];
for(j=2;j<=n;j++)
{
b[j]=b[j-1]+a[j]; //求奇数项的和
cout<<"B的值:"<<b[j]<<" ";
k=1; //清零操作
for(m=2;m<=2*j;m++)//求2n!阶层
k*=m;
cout<<"K的值:"<<k<<" ";
c[j]=k/b[j];
cout<<"C的值:"<<c[j]<<" ";
cout<<endl;
}
for(j=1;j<=n;j++)
{
if(j%2==0)
c[j]=c[j];
else c[j]=-c[j];
p+=c[j];
}
cout<<endl;
cout<<"最终结果:"<<p;
cin>>j;
return 0;
system("pause");
}
貌似我这么写的复杂度高了,再想想高效的算法吧。