[求助]帮帮忙!
求1-1/2+1/3-1/4+...+1/99-1/100的值.用循环怎么做?
{ 1 n=1
sum(n){sum(n-1)+a(n) n>=2
a(n)=(1/n)*(-1)的n次方
用递归较好:
#include<iostream.h>
#include<stdio.h>
float sum(int n)
{ if(n<=0) cout<<"ERROR!! n<=0 \a"<<endl;
else if(n==1) return 1;
else return (sum(n-1)+a(n));
}
float a(int n)
{
if(n/2==0) return -(1/n);
else return 1/n;
}
int main()
{ int n;
cout<<"PLease input the number n"<<endl;
cout<<"n=";
cin>>n;
cout<<"sum["<<n<<"]="<<sum(n)<<endl;
}