2013-10-07 34 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会给结果。