gpt4 book ai didi

c++ - 具有函数模板的递归函数

转载 作者:行者123 更新时间:2023-11-30 02:48:44 25 4
gpt4 key购买 nike

我对编程还很陌生。当我构建这个程序时,我使用 visual express 没有得到任何错误。但是当我在没有调试的情况下运行它时,它会显示第一个 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() 也是 not the right way to define main .

关于c++ - 具有函数模板的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21836011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com