计蒜客 挑战难题 X的平方根
2016-04-17 21:30
363 查看
题目:
设计函数int sqrt(int x),计算x的平方根。
格式:
输入一个数x,输出它的平方根。直到碰到结束符号为止。
千万注意:是int类型哦~
输入可以如下操作:
while(cin>>x)
或者
while(scanf(“%d”, &x) != EOF)
样例1
输入:
输出:
解法1:
二分法
解法2:
牛顿法
参考:
一个Sqrt函数引发的血案
设计函数int sqrt(int x),计算x的平方根。
格式:
输入一个数x,输出它的平方根。直到碰到结束符号为止。
千万注意:是int类型哦~
输入可以如下操作:
while(cin>>x)
或者
while(scanf(“%d”, &x) != EOF)
样例1
输入:
1 2 3 4 5 6 7 8 9
输出:
1 1 1 2 2 2 2 2 3
解法1:
二分法
#include <stdio.h> int nsqrt(int x) { double l=0,h,m=1.0,eps; h = x; eps = x - m*m; while(eps > 0.001) { m = (l+h)/2.0; if(m*m > x) { h = m; eps = m*m - x; } else { l = m; eps = x - m*m; } } return m; } int main(int argc, char *argv[]) { int x; while(scanf("%d",&x) != EOF) printf("%d\n",nsqrt(x)); return 0; }
解法2:
牛顿法
#include <iostream> #include <cmath> using namespace std ; int sqrt(int x) { double t=1.0; while(abs(t*t-x)>1e-5) { t=(x/t+t)/2.0; } return t; } int main() { int x ; while(cin>>x) { cout << sqrt(x) << endl ; } }
参考:
一个Sqrt函数引发的血案
相关文章推荐
- C++二分法在数组中查找关键字的方法
- php二分法在IP地址查询中的应用
- Python实现二分法算法实例
- Python二分法搜索算法实例分析
- 八大方法巧妙排除网络连接故障
- linux kernel data struct: binary search
- nyoj-306-走迷宫--二分法+dfs
- HDU 2199
- 数值计算库中使用设计模式(一)
- 二分法查找对象的引用
- PHP实现二分法查找(递归)
- leetcode:Find Peak Elements 菜鸟解法
- leetcode:Find Minimum in Rotated Sorted Array II 菜鸟解法
- leetcode:Find Minimum in Rotated Sorted Array 菜鸟解法
- leetcode:Search Insert Position菜鸟解法
- 第一次周赛C
- 二分法查找
- poj 3273
- hdu 1969
- 第三周—二分法4 已知面积,求最大体积