一、题目
用迭代法求:
的值。要求精度为0.00001,即
二、迭代公式
求平方根的迭代公式为:
当满足
时,这时的即是求得的根。如果
得到是精确值。如果不为0,则是近似值。
三、C++代码
先给出开平方运算的函数。再给出主程序,主程序中,得到结果 后进行一次验证。
里面很有意思的一点是,当我把精度设 为0.00001时,得到的结果是小数点后5位。但把精度设为0.000001时,结果也是小数点后5位。
//====================================
//sqrt.cpp
//------------------------------------
#include <iostream>
#include <cmath>
using namespace std;
//------------------------------------
double SQRT( double a ) // 迭代法开平方运算
{double y = a ; //double x = 0.0; // 给迭代赋初值while( fabs( y - x ) > 0.00001 ) //迭代精度:0.00001{x = y;y = ( x + a / x ) * 0.5;}return y; //返回迭代结果。
}
//-------------------------------------
int main()
{double a, r;cout << "Please input a digit for squart: " ;cin >> a;while( a < 0 ) //判断输入的数是否小于0。小于0则重新输入。{cout << "The digit is less 0.Please input a digit once." << endl;cin >> a;}r = SQRT( a );cout << "Sqrt(a)=" << r << endl;cout << r * r << endl; //做个验证system( "PAUSE" );return 0;
}
//-------------------------------------------------------