1+1/2-1/3+1/4-1/5+1/6......
#include<iostream.h>float f(int n){
int m=-1;
if(n=1) return 1;
if(n%2==0) return 1.0/n+f(n-1)*m;
else return (1.0/n)*m+f(n-1);
}
void main (){
double n;
cin>>n;
cout<<f(n);}
结果出不来小数,都是1,帮一下
#include<iostream.h> class stack{ private: double*st; int msize; public: int top; stack(){ top=-1; } stack(int size){ msize=size; st=new double[msize]; top=-1; } void push(double n); double pop(); }; void stack::push(double n){ st[++top]=n; } double stack::pop(){ if(top==-1) return 0; else return st[top--]; } void main(){ int n;double m=0;double x; cin>>n; stack s(n); for(int i=n;i>0;i--){ if(i==1) { s.push(1); break; } if(i%2==0) s.push(1.0/i); else s.push(-1.0/i); } while(s.top!=-1){ x=s.pop(); m=m+x; } cout<<m<<endl; }