具有函数模板的递归函数
Recursive function with function template
我对编程相当陌生。当我构建这个程序时,使用视觉表达时没有收到任何错误。但是当我在没有调试的情况下运行它时,它会显示第一个 cout
语句和函数调用的答案number
然后崩溃。谁能告诉我可能出了什么问题?
#include <iostream>
#include <iomanip>
using namespace std;
// This program demonstrates a recursive function.
// The function should accept two arguments, the
// number to be raised and the exponent. A function
// template is used to test different data types.
// Assume that the exponent is a nonnegative integer.
template <class T, class TT>
T number(T raised, TT exponent)
{
if (exponent == 0)
return 1;
else
return raised * number(raised, exponent -1);
}
void main()
{
// Testing integers
cout << "Testing integers: 5 raised to 2 is "
<< number(5, 2) << endl;
// Testing doubles
cout << "Testing doubles: 5.5 raised to 2.2 is "
<< setprecision(1) << number(5.5, 2.2) << endl;
// Testing floats
cout << "Testing doubles: 5.55 raised to 2.22 is "
<< setprecision(4) << number(5.55f, 2.22f) << endl;
// Testing a double and a integer
cout << "Testing integers: 5.5 raised to 2 is "
<< number(5.5, 2) << endl;
}
编辑:感谢您的回复。我现在明白了。我将调整if(exponent == 0)
问题在于递归:
if(exponent == 0) return 1;
你没有考虑的是这个数字是否是一个double
,比如2.2
。将其减少 1 两次后,它将达到 .2
然后-0.8
.它永远不会到达0
.这会导致堆栈溢出,因为递归深度超过堆栈。
此外,void main()
也不是定义 main 的正确方法。
你打破了这个假设:
// Assume that the exponent is a nonnegative integer.
递归函数适用于整数指数,因为最终从指数中减去 1 将得到零,并且函数将返回。
传递一个非整数值,如2.2
,将导致它递归调用带有1.2
、0.2
、-0.8
、-1.8
等函数,直到堆栈爆炸。
在 C++11 中,您可以强制执行假设,例如:
static_assert(std::is_integral<TT>::value, "Exponent must be an integer");
尽管如果整数值太大,您仍然可能会遇到问题。
相关文章:
- 如何在 c++ 的类中递归调用函数方法?
- 递归 pCall 函数
- C++:递归成员函数模板
- 返回未定义行为的递归行列式函数
- 变分模板递归构造函数问题
- 链表中的递归长度函数实现
- n维向量的递归可变参数模板函数
- 具有 4 个指针的节点的递归插入函数返回 null
- 具有编译问题的简单(递归)可变参数模板"accumulate_for"函数
- 为什么这个递归 lambda 函数不安全?
- 递归地将模板传递给模板模板函数
- 使用递归的函数未按预期工作
- 5000+ 深度递归时函数堆栈溢出
- 递归std ::函数定义模板类方法
- 使用模板递归检查函数方法是否存在
- 将递归可变参数模板函数转换为迭代函数
- 使用可变参数模板的递归元函数
- 递归可变参数模板函数调用第二个参数类型的指针"loses"指针
- 具有递归可变参数模板的函数的部分模板专用化的替代方案
- 模板大小递归--构造函数多个重载