一道面试题,实现开根号,有一定限制条件

来源:互联网 发布:打印照片软件 编辑:程序博客网 时间:2024/05/03 18:34

题目:

实现一个函数, 完成 开根号 的操作, 方法签名如下.

double sqrt(int v, double t)

要求:

  1. 不能调用系统库函数, 诸如 Math.sqrt(v) 之类的;

  2. 假设计算出的结果为 r, 要求满足如下条件,   , 其中 是真实的值, t 为给定的一个误差范围, 例如0.1等, 即你计算出的值要在给定的误差范围内. (哭, 公众号文章里不支持 mathjax)

  3. 实现语言不限, 你条件可以比上述更加苛刻, 但不能宽松, 举例而言, 我调用你的接口sqrt(9, 0.21) 返回值属于 [2.79, 3.21] 这个区间的任意一个都满足条件.



//*******************************************************************// NOTE: please read the 'More Info' tab to the right for shortcuts.//*******************************************************************import java.lang.Math; // headers MUST be above the first class// one class needs to have a main() methodpublic class HelloWorld{  public static double sqrt(int v, double t){    if(t<0){    t *= -1;    }  double u = v/(t*t);    int s = 0;    while(s*s<=u){    s++;    }    return (s-1)*t;  }  // arguments are passed using the text field below this editor  public static void main(String[] args)  {    System.out.print(sqrt(0,0.21));  }}


0 0
原创粉丝点击