编程手动平方根函数?

时间:2017-09-21 10:49:29

标签: c++ math inclusion

对于我的班级,我正在使用包含编写平方根函数。不,我可能不会使用任何其他方法...

这是我的代码到目前为止,该程序几乎正常工作。它适用于完美的平方根和其他一些值(如11或5),但它会进入其他的无限循环(8,2)。

发生这种情况的原因是上限和下限(b和a)不会改变。理想情况下,边界将是当前x和前一个x,从而创建新的x。会发生什么是新的x当前由当前的x和a或b形成,是一个常数。

我已经尝试了很长时间,但我还没有找到“记住”或找到'前一个x'的方法,因为每次while循环重复时,只有当前的x可供使用。有谁知道如何解决这个问题?

void inclusion ()
{
    double v ;
    cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
    cin >> v ;

    while (v<0)
    {
        cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
        cin >> v ;
    }

    cout << endl ;

    int n = 0;
    while (v >= n*n)
        n++ ;

    double b = n ;
    double a = n-1 ;

    int t = 0 ;
    double x = (a+b)/2 ;

        while ((x * x - v >= 0.1) || (x * x - v <= -0.1))
        {
            t++ ;

            if (x * x < v)
                {
                cout << "Lower Bound: " << x << '\t' << '\t' ;
                cout << "Upper Bound: " << b << '\t' << '\t' ;
                x = (b + x)/2 ;
                cout << "Approximation " << t << ": " << x  << endl ;
                }

            else
                {
                cout << "Lower Bound: " << a << '\t' << '\t' ;
                cout << "Upper Bound: " << x << '\t' << '\t' ;
                x = (a + x)/2 ;
                cout << "Approximation " << t << ": " << x  << endl ;
                }
        }

    cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}

2 个答案:

答案 0 :(得分:2)

  

我还没有找到“记住”或找到'前一个x'的方法

在循环结束时有previous_x变量previous_x = x

但那不是你的问题。您正在更改x,而不是ab,因此您会进入无限重复的模式。你应该调整哪个绑定会让你更紧张。

void inclusion ()
{
    double v ;
    cout << "*** Now solving using Inclusion ***" << endl << "To calculate the square root, enter a positive number: " ;
    cin >> v ;

    while (v<0)
    {
        cout << "Square roots of negative numbers cannot be calculated, please enter a positive number: " ;
        cin >> v ;
    }

    cout << endl ;

    int n = 0;
    while (v >= n*n)
        n++ ;

    double b = n ;
    double a = n-1 ;

    int t = 0 ;

    double x;
    for (x = (a+b)/2; abs(x * x - v) >= 0.1; x = (a+b)/2, ++t)
    {
        if (x * x < v)
        {
            cout << "Lower Bound: " << x << '\t' << '\t' ;
            cout << "Upper Bound: " << b << '\t' << '\t' ;
            a = (b + x)/2 ;
            cout << "Approximation " << t << ": " << x  << endl ;
        }   
        else
        {
            cout << "Lower Bound: " << a << '\t' << '\t' ;
            cout << "Upper Bound: " << x << '\t' << '\t' ;
            b = (a + x)/2 ;
            cout << "Approximation " << t << ": " << x  << endl ;
        }
    }

    cout << endl << "The answer is " << x << ". Iterated " << t << " times." << endl << endl ;
}

答案 1 :(得分:1)

您还需要更新边界:

a = x;
x = (b + x)/2;

b = x;
x = (a + x)/2;