设计函数int sqrt(int x),计算x的平方根。

格式:

   输入一个数x,输出它的平方根。直到碰到结束符号为止。

   千万注意:是int类型哦~

   输入可以如下操作:

while(cin>>x)

或者

while(scanf("%d", &x) != EOF) 

样例输入

1
2
3
4
5
6
7
8
9

样例输出

1
1
1
2
2
2
2
2
3
分析:写出函数表达式,f(Xn) = Xn^2 - x;然后用牛顿迭代法,求出近似解,取其整数部分即为所求。
 1 #include <iostream>
 2 #include <cmath>
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 int sqrt(int x){
 7     double t = 1.0;
 8     while(fabs(t * t - x) > 1e-6){
 9         t = (t + x / t) / 2;
10     }//牛顿迭代法
11     return t;
12 }
13 
14 int main(){
15     int x;
16     while(scanf("%d", &x) != EOF){
17         printf("%d\n",sqrt(x));
18     }
19     return 0;
20 }

 

相关文章:

  • 2021-04-02
  • 2021-08-25
  • 2021-07-10
  • 2021-10-29
  • 2021-11-28
  • 2021-06-20
  • 2021-12-02
  • 2021-10-06
猜你喜欢
  • 2022-12-23
  • 2021-06-25
  • 2021-11-27
  • 2021-04-20
  • 2021-07-27
  • 2021-10-26
相关资源
相似解决方案