在写代码时,你会怎么去求一个数的平方根呢?

    用编程语言自带的math函数?

    如果没有没有math函数呢?

 

    想一想……

 

    下面分享一个我看到的算法。

 1 def sqrt(x):
 2     ans = 0
 3     if x >= 0 :
 4     while ans * ans < x :
 5         ans += 1
 6         if ans * ans != x :
 7             print x, 'is not a perfect square.'
 8             return None
 9         else :
10                 return ans
11     else :
12     print x, 'is a negative number!!'
13     return None

 

    测试一下。

  奇妙的算法(2)—— 求平方根

 

    当然,这个算法并不完美 —— 只能计算平方根刚好是整数的数。

    我只是想分享下这样的一个算法。

 

    (说明:上面的截图是在Python的IDLE下)

 

 

相关文章:

  • 2022-12-23
  • 2021-10-22
  • 2021-12-26
  • 2021-12-22
  • 2022-12-23
  • 2021-11-02
  • 2021-11-08
  • 2021-06-26
猜你喜欢
  • 2021-08-22
  • 2019-08-24
  • 2021-07-15
  • 2022-03-06
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案