标题:用牛顿法求N次方根
只看楼主
baoyibao
Rank: 1
等 级:新手上路
帖 子:29
专家分:0
注 册:2008-3-13
 问题点数:0 回复次数:0 
用牛顿法求N次方根
// 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 );
    }
}
搜索更多相关主题的帖子: 牛顿 方根 
2008-03-19 12:16



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-204163-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.129983 second(s), 10 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved