具有函数模板的递归函数

Recursive function with function template

本文关键字:递归函数 函数模板      更新时间:2023-10-16

我对编程相当陌生。当我构建这个程序时,使用视觉表达时没有收到任何错误。但是当我在没有调试的情况下运行它时,它会显示第一个 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.20.2-0.8-1.8等函数,直到堆栈爆炸。

在 C++11 中,您可以强制执行假设,例如:

static_assert(std::is_integral<TT>::value, "Exponent must be an integer");

尽管如果整数值太大,您仍然可能会遇到问题。