2015-06-11 131 views
-4

我想調用這個遞歸方法,但我不明白爲什麼它沒有達到else語句返回mul。我在主函數中傳遞值0,它小於n,並且在x變得大於n時,它應該移動到else函數。控制到達非空函數結束

#include <cmath> 
#include <cstdio> 
#include <vector> 
#include <iostream> 
#include <algorithm> 
using namespace std; 
int n,mul=0; 
vector <int> a; 

int calc(int x) 
{ int mul,chk; 

int l=n; 
if(x<n) 
{ 
    chk=a[x]*(l-1); 
    l--; 
    if(mul<chk) 
     { 
      mul=chk; 
    } 

    calc(x+1); 
     } 

    else 
    { return mul;} 

    } 

int main() { 

cin>>n; 
for(int i=0;i<n;i++) 
    cin>>a[i]; 
sort(a.begin(),a.end()); 

int z=calc(0); 
cout<<z; 

return 0; 
} 
+0

「它沒有達到else語句」。示例代碼中的任何地方都沒有「else」關鍵字。 –

+0

正確地格式化您的代碼,將使診斷此問題的源更加容易。 –

回答

0

Wihtout知道確切的錯誤信息,我不是100%確定是什麼問題,但我想它是這樣的:

你的函數看起來像這樣(簡化):

int calc(int x) { 
    if(someCondition){ 
     if(otherCondition){} 
     calc(x+1); 
    } else { 
     return mul; 
    } 
} 

問題是,如果someConditiontrue,該函數不會返回任何內容。你可能想要做的:

return calc(x+1); 

,而不是僅僅

calc(x+1); 
相關問題