试图弄清楚如何使用递归来获得与另一个函数相同的答案
Trying to figure out how to use recursions to get the same answer as another function
我可以在编程作业中使用一些帮助。我需要使用递归才能使arithmetic_series = arithmetic_series_recursive。现在我的递归函数无法正常工作。它只工作到数字三。这些函数应该从用户那里获取输入,并根据数字内的整数数形成一个数字。IE 如果用户输入 3,则为 1*2*3 = 6。
int arithmetic_series(int n){
int total = ((n+1) * n )/ 2;
cout << total << endl;
return total;
}
int arithmetic_series_recursive(int n){
if(n==1){
return 1;
}else{
return n*arithmetic_series_recursive(n-1);
}
}
你的第一个函数找到从 1
到 n
的整数之和。您的第二个函数查找该范围的乘积,或!n
。我不知道您可以在第一个函数中使用任何简化。
如果你想找到数字的总和,你可以改变你的第二个函数来执行加法:
int arithmetic_series_recursive(int n) {
if (n == 1) {
return 1;
}
else {
return n + arithmetic_series_recursive(n - 1);
}
}
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何在qt中从另一个类调用函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 将 N-arg 函数包装到另一个函数中
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C++从另一个函数退出函数
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 在一个类中使用另一个类中的函数,而不在 c++ 中使用继承
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?