2013-10-07 85 views
0

我知道這是錯誤的,但只是學習如何做遞歸函數並試圖理解如何更好地工作。在遞歸函數中計算大寫字母

#include <iostream> 
    using namespace std; 


    int getUpper (const string& s, int high) { 

     int count=0; 


     if(s.size()>0) { 

     if (s[0] <='Z' && s[0] >='A') 
      count++; 

     return getUpper(s.substr(1,s.size()-1), high-1); 

    } 
    return count; 
} 

    int getUpper (const string& s){ 
     int high=s.size()-1; 

     int count=getUpper(s,high); 
     return count; 
    } 


    int main() 
    { 
    string s="WeLC"; 
    int value=getUpper(s); 
    cout << value; 
     return 0; 
    } 

爲什麼這不返回計數數? 4.

+0

作爲一個方面說明,'std :: count_if'是這樣做的正確方法。 – chris

回答

0

一個提示:getUpper返回值,不包含count

return getUpper(s.substr(1,s.size()-1), high-1); // no `count` 

BTW,getUpper("WeLC")應該返回3,不4

0

認識到0123'的每個遞歸調用都有自己的局部變量count的副本。 count++沒有做任何有用的事情,因爲這個變量在增量後沒有被用於任何事情。

0

的暴露出的問題當u調用每個TYM你的函數計數所以最終初始化這將是0在最後TYM它called.So更好的解決辦法的是有數量爲全球var.For如

int count1=0; 

INT getUpper(const string & s,int high){

int count = 0; 如果(s.size()> 0){

 if (s[0] <='Z' && s[0] >='A') 
     count++; 
    count1++; 

    return getUpper(s.substr(1,s.size()-1), high-1); 

} 
return count1; 

}

現在COUNT1會給結果。