首先,我想说这是我第一次尝试为我的编程类做递归函数!无论如何,该任务是使用递归找到任何正整数的根(绝对没有迭代)。我的代码正确地评估了任何正数的平方根,但是当我试图说出数字的第四根或第三根时,我得到了堆栈溢出错误。我会发布我的代码和任何帮助将不胜感激。如果你觉得需要哈哈,就冲出去吧。帮助堆栈溢出问题!
#include<iostream>
#include<iomanip>
#include<cstdlib>
using namespace std;
double squareRoot (int root, double number, double low, double high);
int main() {
int root = 0;
double number;
double low, high;
double guess = 0;
double error = 0;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
do
{
cout << "Find what root? (0 ends): ";
cin >> root;
if (root == 0)
{
exit(1);
}
else
{
cout << "Root of what value? ";
cin >> number;
}
low = number - (number - 1);
high = number;
cout << "root " << root << " of " << setprecision(4) << number << " is " << setprecision(10) << squareRoot (root, number, low, high) << endl;
}while (root != 0);
cin.get();
cin.get();
return 0;
}
double squareRoot (int root, double number, double low, double high)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(10);
double guess = (high + low)/double(root);
double error = abs(number - (guess * guess));
if ((guess * guess) == number || error <= 0.000000000001)
{
return guess;
}
else if ((guess * guess) > number)
{
high = guess;
return squareRoot(root, number, low, high);
}
else
{
low = guess;
return squareRoot(root, number, low, high);
}
}
你知道错误发生在哪一点吗?你有没有试过调试你的程序? – 2011-04-18 06:14:51
由于''squareRoot()'函数没有做任何I/O,它不应该修改'cout'的属性;这是功能混合不良。 – 2011-04-18 06:16:33
我确实调试了我的程序,并且从我的解释看来,else语句中的“return squareRoot”函数发生错误。看起来好像我的函数中的else语句被调用了很多次,并且空间不足?我确信在这个计划中有一个更有效率的方法,但我错过了。 – Riordan 2011-04-18 06:19:19