我知道这是错误的,但是只是学习如何做递归函数并试图理解如何更好地解决这个问题。
#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。
意识到每个递归调用getUpper
都有自己的局部变量副本count
。 count++
不会做任何有用的事情,因为该变量在增量后实际上并未用于任何用途。
一个提示:getUpper
返回值而不合并count
。
return getUpper(s.substr(1,s.size()-1), high-1); // no `count`
顺便说一句,getUpper("WeLC")
应该返回3
,而不是4
.
问题 s 当你调用每个 tym 时,你的函数计数被初始化,所以最终它在它调用的最后一个 tym 将是 0。因此,更好的解决方案是算作全局变量。例如
int count1=0;
int getUpper ( const string& s, int high( {
整数计数=0; if(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 将给出结果。