帮助Stack Overflow问题!

时间:2011-04-18 06:09:46

标签: c++

首先,我想说这是我第一次尝试为我的编程类做一个递归函数!无论如何,赋值是使用递归找到任何正整数的根(绝对没有迭代)。我的代码正确地评估了任何正数的平方根,但是当我试图说出数字的第四个根或第三个根时,我得到一个堆栈溢出错误。我将发布我的代码,任何帮助将非常感激。如果你觉得需要哈哈就会爆炸。

#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); 
    }
}

3 个答案:

答案 0 :(得分:3)

你得到一个堆栈溢出,因为你无限递归;你永远找不到答案。

拿一支铅笔和一张纸,然后通过一个输入(比如3表示root,8表示值)来完成你的递归...找出你解决逻辑无效的原因。

答案 1 :(得分:1)

在递归中存在问题,堆栈溢出是递归函数的常见问题,退出条件可能有问题。

如上所述,拿铅笔&amp;纸并开始挖掘。

答案 2 :(得分:0)

这是一个提示:

您的功能称为squareRoot,并且在多个位置包含guess * guess,那么int root参数是什么?