注册 登录
编程论坛 C++教室

用牛顿法求N次方根

baoyibao 发布于 2008-03-19 12:16, 1103 次点击
// File: nth_root.cpp
/*
  Author: baoyibao
  Date: 2008/3/19
  Version: 1.0
*/

#include <iostream>
#include <cmath>

#define EPS 1.0e-6

// calculate the nth root of x using Newton algorithm
double nth_root( double x, int n, double guess );

int main()
{
    using namespace std;
   
    double x;
    int n;
    int cont = 1;
   
    while( cont )
    {
        cout << "Input x and n:\n>";
        cin >> x >> n;
        cout << "The nth root of x is: " << nth_root( x, n, x/n) << endl;
        cout << "Continue(1=YES/0=NO)?\n>";
        cin >> cont;
        while( cont < 0 || cont > 1 )
        {
            cout << "Wrong choice! Continue(1=YES/0=NO)?\n>";
            cin >> cont;
        }
    }
}

double nth_root( double x, int n, double guess )
{
    double guess_of_x = pow( guess, n );
   
    if ( (guess_of_x - x < EPS) && (guess_of_x - x > -EPS) )
        return guess;
    else
    {
        guess = ( x / pow( guess, n - 1) + guess * ( n - 1 ) ) / n;
        return nth_root( x, n, guess );
    }
}
0 回复
1