今天筆者突然想用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上運行如下圖所示:

