Liny_@NotePad

沉迷ACG中

用递归算法求解f(x)=x/2+x^2/4+...+x^n/2^n

YOYO posted @ 2009年3月10日 20:11 in 【算法】与【数据结构】 with tags 递归 , 5509 阅读

用递归算法求解如下问题:

f(x)=$\frac{x}{2}$$+\frac{x^2}{4}+...+\frac{x^n}{2^n}

 

递归公式:f(x)=$\begin{Bmatrix}\frac{x}{2} & x=1\\ (f(x-1)+1)*\frac{x}{2} & x>1

  1. #include<iostream>
  2. using namespace std;
  3.  
  4. float countFx(float x, int p){
  5.         if(p==1)return x/2;
  6.  
  7.         return (countFx(x,p-1)+1)*x/2;
  8. }
  9.  
  10. int main(){
  11.         float x;
  12.         int n;
  13.  
  14.         cout<<"请输入要求的x和n:";
  15.         cin>>x>>n;
  16.  
  17.         cout<<"f("<<x<<")="<<countFx(x,n)<<endl;
  18.  
  19.         return 0;
  20. }

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter