帮助堆栈溢出问题!

问题描述

| 首先,我想说这是我为编程类做递归函数的第一次尝试!无论如何,分配是使用递归(绝对没有迭代)来找到任何正整数的根。我的代码正确计算了任何正数的平方根,但是当我尝试说一个数的第四根或第三根时,出现堆栈溢出错误。我将发布我的代码,任何帮助将不胜感激。如果您认为需要,请高吹。
#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 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,high); 
    }
    else
    {
        low = guess; 
        return squareRoot(root,high); 
    }
}
    

解决方法

由于无限递归,您将获得堆栈溢出;你永远找不到答案。 拿一支铅笔和纸,用输入完成遍历递归(例如3表示根,8表示值)...找出为什么您的求解逻辑不起作用。     ,您在递归中遇到问题,堆栈溢出是递归函数的常见问题,您的退出条件可能是错误的。 如上所述,拿铅笔和纸开始学习。     ,这是一个提示: 您的函数称为
squareRoot
,它在多个位置包含
guess * guess
,那么
int root
参数的作用是什么?     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...