zoukankan      html  css  js  c++  java
  • 计蒜客 X的平方根

    设计函数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
    ",sqrt(x));
    18     }
    19     return 0;
    20 }
  • 相关阅读:
    openwrt 的依赖找不到问题
    数据包与IPTABLE关系
    wifidog 配置中文说明
    Java 线程
    Java 集合
    IDEA配置Maven并创建web项目
    逻辑覆盖
    获得天气数据
    小程序项目文件介绍
    window 10 使用git
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/6262949.html
Copyright © 2011-2022 走看看