首页 > 编程语言 > 详细

C++(迭代法求平方根)

时间:2020-05-05 12:03:36      阅读:80      评论:0      收藏:0      [点我收藏+]

  今天笔者突然想用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 }
square.cpp

结果在vs2017上运行如下图所示:

技术分享图片

C++(迭代法求平方根)

原文:https://www.cnblogs.com/xuelanga000/p/12830021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!