[英]counting upper case letters in recursive function
我知道這是錯誤的,但是只是學習如何執行遞歸函數並試圖了解如何更好地解決這一問題。
#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
。
return getUpper(s.substr(1,s.size()-1), high-1); // no `count`
順便說一句, getUpper("WeLC")
應該返回3
,而不是4
。
意識到getUpper
每個遞歸調用都有其自己的局部變量count
副本。 count++
並沒有做任何有用的事情,因為在增加之后,變量實際上並沒有被使用。
問題是當您調用每個tym時,您的函數計數將被初始化,因此最終在調用的最后一個tym處它將為0,因此更好的解決方案是將計數計為全局變量。
int count1=0;
int getUpper(const string&s,int high){
int count = 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將給出結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.