HDU1012 Calculate e

68 篇文章 1 订阅

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1012

解法一:最直观的方法,就是递归计算来求各项之和

#include  < iostream >
#include 
< iomanip >
using   namespace  std;

double  curItem( int  n)
{//当前子项
    if (n==0)
    
{
        
return 1;
    }

    
else
        
return curItem(n-1)/n;

}

double  sum( int  n)
{
    
if(n==0)
        
return 1;
    
else 
        
return sum(n-1)+curItem(n);

}

void  caculateE( int  n)
{//输出指定n下e的值
    double tmp1,tmp2=1.0f,result=0.0f;
    
int i;
    result 
= sum(n);
    
if(n==0||n==1)
    
{
        cout
<<n<<" "<<static_cast<int>(result)<<endl;
    }

    
else if(n==2)
    
{
        cout
<<setiosflags(ios::fixed)<<setprecision(1);
        cout
<<n<<" "<<result<<endl;
    }

    
else
    
{
        cout
<<setiosflags(ios::fixed)<<setprecision(9);
        cout
<<n<<" "<<result<<endl;
    }

}

int  main( int  argc,  char   * argv[])
{
    
int n,i;
    cout
<<"n e"<<endl;
    cout
<<"- -----------"<<endl;
    
for(i=0;i<=9;++i)
    
{
        caculateE(i);
    }

    cin
>>i;
    
return 0;
}

解法二: 题中给出的计算e的式子是由e^x的泰勒级数展开而得,在计算之前可以使用个技巧,就是把它们叠乘起来改写成:
e=(1
+(1+1/2(1+1/3(1+1/4(1+…1/(n-1)(1+1/n)))) ,从最里面的括号往外算,共做n次除法和加法得一段结果,运算效率也是O(N*M),但是由于收敛速度快些,所以N项节省一些,

#include  < iostream >
#include 
< iomanip >
using   namespace  std;

double  doCaculate( int  n)
{//实际的计算
    double tmp1,tmp2=1.0f,result=0.0f;
    
int i;

    
for(i=n;i>=1;--i)
    
{
        tmp1 
= static_cast<double>(1)/static_cast<double>(i);
        tmp2 
= 1.0f+tmp1*tmp2;
    }

    
return tmp2;
}

void  caculateE( int  n)
{//输出指定n下e的值,主要是输出格式的处理
    double result = 0.0f;
    result 
= doCaculate(n);
    
if(n==0||n==1)
    
{
        cout
<<n<<" "<<static_cast<int>(result)<<endl;
    }

    
else if(n==2)
    
{
        cout
<<setiosflags(ios::fixed)<<setprecision(1);
        cout
<<n<<" "<<result<<endl;
    }

    
else
    
{
        cout
<<setiosflags(ios::fixed)<<setprecision(9);
        cout
<<n<<" "<<result<<endl;
    }

}

int  main( int  argc,  char   * argv[])
{
    
int n,i;
    cout
<<"n e"<<endl;
    cout
<<"- -----------"<<endl;
    
for(i=0;i<=9;++i)
    
{
        caculateE(i);
    }

    
return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值