非递归实现(栈方法):1 + 1/2 - 1/3 + 1/4 - 1/5.......

来源:互联网 发布:同花顺股票模拟软件 编辑:程序博客网 时间:2024/05/18 14:14

/* 非递归实现(栈方法):
*
* 1 + 1/2 - 1/3 + 1/4 - 1/5…….
*/

/*    非递归实现(栈方法): *     *     1 + 1/2 - 1/3 + 1/4 - 1/5....... */#include<stdio.h>#include<stdlib.h>#define OK 1#define ERROR 0#define MAXSIZE 20typedef double ElemType;typedef int Status;typedef struct{    ElemType data[MAXSIZE];    int top;}Sqstack;//顺序栈的初始化Status InitSqstack(Sqstack * S){    S->top=-1;    return OK;}//顺序栈的出栈Status Pop(Sqstack * S,ElemType * e){    *e=S->data[S->top--];    return OK;}//顺序栈的入栈Status Push(Sqstack * S,ElemType e){    S->data[++S->top]=e;    return OK;}double Recursion(Sqstack * S,int n){    ElemType m=0;    ElemType result=0;    ElemType temp;    while(n>0)    {        if(n==1 || n%2==0)        {            m=1.0/n;        }        else        {            m=-(1.0/n);        }        Push(S,m);        n--;    }    while(S->top!=-1)    {        Pop(S,&temp);        result+=temp;    }    return result;}int main(){    Sqstack S;    int n;    InitSqstack(&S);    printf("请输入n的值:\n");    scanf("%d",&n);    double result=Recursion(&S,n);    printf("结果为:%lf\n",result);    return 0;}
0 0
原创粉丝点击