华为机试—求数的平方根立方根
2015-06-27 16:52
204 查看
求一个正整数X的平方根Y,立方根Z。
求平方根和立方根我们一般用牛顿迭代法,下面是对应的公式。
平方根迭代公式a(n+1)=(a(n)+Y/a(n))/2,其中Y为待求平方根。
立方根迭代公式a(n+1)={2a(n)+Z/{[a(n)]^2}}/3,其中Z为待求平方根。
java
求平方根和立方根我们一般用牛顿迭代法,下面是对应的公式。
平方根迭代公式a(n+1)=(a(n)+Y/a(n))/2,其中Y为待求平方根。
立方根迭代公式a(n+1)={2a(n)+Z/{[a(n)]^2}}/3,其中Z为待求平方根。
java
import java.util.Scanner; public class cubeSquare { public double sqrt_root(double a, double x0) { double x1, y; x1 = (x0 + a / x0) / 2.0; if (Math.abs(x1 - x0) >= 0.00001) y = sqrt_root(a, x1); else y = x1; return y; } public double cube_root(double a, double x0) { double x1, y; x1 = (2 * x0 + a / (x0 * x0)) / 3.0; if (Math.abs(x1 - x0) >= 0.00001) y = cube_root(a, x1); else y = x1; return y; } public static void main(String[] args) { cubeSquare cs = new cubeSquare(); Scanner s = new Scanner(System.in); double x = s.nextDouble(); System.out.println(cs.sqrt_root(x, 1.0) + ":" + cs.cube_root(x, 1.0)); } }
#include <math.h> #include <stdio.h> double sqrt_root(double a,double x0) { double x1,y; x1=(x0+a/x0)/2.0; if(fabs(x1-x0)>=0.00001) y=sqrt_root(a,x1); else y=x1; return y; } double cube_root(double a,double x0) { double x1,y; x1=(2*x0+a/(x0*x0))/3.0; if(fabs(x1-x0)>=0.00001) y=cube_root(a,x1); else y=x1; return y; } int main() { double x; printf("Enter x: "); scanf("%lf",&x); printf("The square root of %lf is %f \n",x, sqrt_root(x,1.0)); printf("The cube root of %lf is %f \n",x, cube_root(x,1.0)); return 0; }
相关文章推荐
- Java回调函数的理解
- ContentProvider异常:Caused by: java.lang.SecurityException: Permission Denial
- SqlServer性能急剧下降,查看所有会话的状态及等待类型---Latch_Ex
- boost 安装
- 网页设计用户体验不可缺失的几个方面
- Redis 跳跃表的实现
- 2
- LintCode-编辑距离
- HTTP协议
- ENode框架Conference案例分析系列之 - Quick Start
- 最长上升子序列
- 【华为oj】矩阵乘法
- Java、jsp、JavaScript的三者的区别与联系
- AngularJS中的provider,factory,service方法
- neo4j介绍
- C++ 移位运算 浅析
- 【SPOJ TSUM】Triple Sums(FFT+容斥定理)
- android JBOX2D粒子碰撞的实例,以达到特殊效果
- 使用View.inflate时root为空导致外层布局width和height失效
- CentOS 6.6 yum 搭建LAMP环境