如何开平方
来源:互联网 发布:mac os x 10.12下载 编辑:程序博客网 时间:2024/04/30 01:42
设计一个函数int sqrt(int x),求 一个数的平方根。如果此数不是完全平方数,则输出最大可以是谁的平方。
eg:输入1 2 3 4 5 6 7 8 9,输出1 1 1 2 2 2 2 2 3
方法一:可以采取二分查找,代码如下
#include<stdio.h>int sqrt(int x){int low=1,high=x,mid,res,tmp;while(low<high){mid=(low+high)/2;tmp=mid*mid;if(tmp==x) return mid;else if(tmp>x) high=mid-1;else low=mid+1;}mid=(low+high)/2;tmp=mid*mid;if(tmp>x) mid--; res=mid; return res;}int main(){ int x; while(scanf("%d",&x) != EOF){ printf("%d\n",sqrt(x)); } return 0;}
方法二:
采取牛顿迭代法
#include<stdio.h> #include<math.h>int sqrt(int x){int res=x,tmp;tmp=abs(res*res-x); while(tmp>0.00001){ res=(res+x/res)/2; tmp=abs(res*res-x); } return res;}int main(){ int x; while(scanf("%d",&x) != EOF){ printf("%d\n",sqrt(x)); } return 0;}
参考网址
http://www.cnblogs.com/xkfz007/archive/2012/05/15/2502348.html
0 0
- 如何开平方
- 不用sqrt如何在C语言中开平方
- SQL 开平方
- 整数开平方
- 支点(开平方实践)
- SQL 开平方
- 开平方算法
- 开平方算法
- 求开平方
- 迭代法开平方
- java高精度开平方
- 开平方算法
- 九章算术 开平方
- 高精度开平方
- 开平方实现
- 牛顿法开平方
- 118.开平方
- 牛顿法开平方
- 威佐夫博弈
- NSOprationQueue 与 GCD 的区别与选用
- HTML5 之 图片墙
- Ardupilot 3.5.0:Quadplane/ardupilot plane 3.5.0垂直起降翻译
- 威佐夫博弈
- 如何开平方
- Java 设计模式 - 装饰模式
- ubuntu 上连接服务器
- how to use flux in ubuntu
- 1002-Strange fuction
- 【mail stone】:里程碑记录
- socket
- 结尾想法
- PHP之namespace