我目前正在攻读信息系统学士学位的最后一年,主修编程。我参加了并通过C++编程 1。我现在正在C++编程 2 并且遇到递归函数的问题。我们有一个家庭作业,假设我们编写一个程序来计算用户输入的字符串中的元音数。我有一个类似于我的 C++ 编程 1 类的程序,它使用 for 循环和 if-then 语句工作。我以为转换这个工作程序很容易使用递归函数,我错了。我有代码(不是找人为我做(,我认为我设置正确。只是不确定在函数中将函数调用放在何处。有人能为我指出正确的方向吗?这是我第一次问问题。如果我附错了代码,请告诉我。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int vowelCount(string, int, int&);
int mail()
{
string input;
int len;
//int x;
//int y;
int count;
count = 0;
cout << "Enter a string of characters with no spaces: ";
cin >> input;
len = input.length();
vowelCount(input, len, count);
cout << "There were " << count << " vowels." << endl;
system("pause");
return 0;
}
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
if (len == 1)
{
count = count + 1;
return count;
}
else
{
y = input.at(len);
if ((y == 'a') || (y == 'e') || (y == 'i') || (y == 'o') || (y == 'u') || (y == 'A') || (y == 'E') || (y == 'I') || (y == 'O') || (y == 'U'))
{
count = count + 1;
len = len - 1;
}
else
{
len = len - 1;
vowelCount(string input, int len, int& count);
return count;
}
}
}
return 0;
}
为了大致理解,我推荐这个问题的答案。
首先,这段代码不运行:它有语法错误。 在你有一个至少可以运行的程序之前,你不应该寻求逻辑帮助。 不能调用具有整个签名的函数。 FOr 实例,最后一个块应该是一个简单的
return vowelCount(input, len-1)
将计数作为函数的值和参数返回。 删除参数。
现在,为了理解递归...只需几个步骤即可完成此操作:
- 如果字符串为空,则返回 0。
- 否则,请检查当前信件:
2T 如果是元音,则返回 1 + {字符串其余部分计数}
2F 否则,返回 {计数字符串的其余部分}
您的两个递归调用位于大括号中。 你能从这里拿走吗?
我会按以下方式编写函数
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
std::string::size_type vowelCount( const std::string &input, std::string::size_type pos = 0 )
{
const char *vowels = "AEIOU";
return pos >= input.size()
? 0
: ( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
+ vowelCount( input, pos + 1 );
}
int main()
{
std::string s;
std::cin >> s;
std::cout << "There were " << vowelCount( s ) << " vowels." << std::endl;
return 0;
}
例如,如果输入
AaBbCcDdEe
然后输出将是
There were 4 vowels.
我想字符串不包含嵌入的零字符:)否则,您应该替换条件
( std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
为
( input[pos] != ' ' && std::strchr( vowels, std::toupper( ( unsigned char )input[pos] ) ) != nullptr )
至于你的函数,那么如果编写它在语法上有效,它没有意义,因为例如这个语句
int vowelCount(string input, int len, int& count)
{
int y;
int x;
y = input.at(len);
^^^^^^^^^^^^^^^^^^
因为根据C++标准成员函数at
5 次投掷:如果 pos>= size(( out_of_range。