實用演算法的分析與程式設計——遞推法(順推法)包含執行個體,代碼

來源:互聯網
上載者:User

標籤:遞推法   順推法   代碼   c++   

順推法即由邊界條件出發,通過遞推關係式推出後項值,再由後項值按遞推關係式推出再後項值。。。依次遞推,直至從問題初始陳述向前推進到這個問題的解為止。執行個體

代碼
#include<iostream>#include<stdlib.h>using namespace std;const int maxN = 60 ;int N = 4 ,d = 2 , m = 3;float a1 = 2 ,an = 5;void input(){    cout<<"input data N,d,a1,an,m"<<endl;    cin>>N>>d>>a1>>an>>m;    if( N > maxN )    {        cout<<"input error"<<endl;        return ;    }    if( N > m )    {        cout<<" m is too large "<<endl;        return ;    }    if( m < 0 )    {        cout<<"m must be a positive data."<<endl;        return;    }}//計算am與a1之間的關係s//a[i] = s[m][0]*a[2] + s[i][1]*d + s[i][2]*a1//a2 = ( an - s[N-1][1] * d - s[N-1][2] * a1 ) / s[N-1][0]void calculate_s(float  **s ,float *list){    s[0][0] = 0;    s[0][1] = 0;        s[0][2] = 1;    s[1][0] = 1;    s[1][1] = 0;        s[1][2] = 0;    for(int i = 2 ; i < N ; i++ )    {        s[i][0] = s[i-2][0] - 2 * s[i-1][0];        s[i][1] = s[i-2][1] - 2 * s[i-1][1] + 2;        s[i][2] = s[i-2][2] - 2 * s[i-1][2];    }    list[0] = a1;    list[1] = ( an - s[N-1][1] * d - s[N-1][2] * a1 ) / s[N-1][0] ;    for(int j = 2 ; j < N ; j++ )    {        list[j] = list[j-2] - 2*list[j-1] +2 * d;    }}//輸出最後的結果void out(float  **s ,float *list){    int i;    for(i = 0 ;i < N ; i++ )    {        cout<<s[i][0]<<" "<<s[i][1]<<" "<<s[i][2]<<" "<<endl;    }    cout<<"data........"<<endl;    for(i = 0 ;i < N ; i++ )    {        cout<<list[i]<<" ";    }    cout<<endl;}int main(){    //input();    //s[i][0]表示p s[i][1]表示q s[i][2]表示r    float **s = (float **)malloc(sizeof(float*) * N);    for(int ii = 0 ; ii < N ; ii++ )        s[ii] = (float *)malloc(sizeof(float) * 3);     float *list = (float *)malloc( sizeof(float) * N );     calculate_s(s , list );    out( s , list );    cout<<"\nthe result of "<<m<<"  data is:";    cout<<list[m-1]<<endl;    return 0;}

實用演算法的分析與程式設計——遞推法(順推法)包含執行個體,代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.