C++(迭代法求平方根)
今天笔者突然想用C++实现求平方根的程序,整体的思路是采用迭代法
首先,写出迭代表达是Xk+1=0.5*(Xk+Y/Xk),由于笔者只是求解近似解,
所以,我为的控制了迭代的次数,选择5次。代码如下:
1 #include <iostream> 2 using namespace std; 3 class square { 4 public: 5 square(float x, float y) { 6 this->x = x; 7 this->y = y; 8 } 9 void it_root() { 10 x = 0.5f*(x + y / x); 11 } 12 float getX() const { return x; } 13 float getY() const { return y; } 14 private: 15 float x, y; 16 }; 17 18 19 20 int main() 21 { 22 square root(1,3); 23 for (int i = 0; i < 5; ++i) { 24 root.it_root(); 25 } 26 std::cout << root.getX() << endl; 27 28 std::cout << "Hello World!\n"; 29 }
结果在vs2017上运行如下图所示: