Easiest way to find Square Root in Swift?

前端 未结 6 1855
小鲜肉
小鲜肉 2021-02-18 22:00

I have been trying to figure out how to programmatically find a square root of a number in Swift. I am looking for the simplest possible way to accomplish with as little code ne

6条回答
  •  孤城傲影
    2021-02-18 22:30

    func sqrt(num:Int)-> Double {
        var x1:Double = (Double(num) * 1.0) / 2; 
        var x2:Double = (x1 + (Double(num) / x1)) / 2; 
        while(abs(x1 - x2) >= 0.0000001){
            x1 = x2; 
            x2 = (x1 + (Double(num) / x1)) / 2;
            }
        return Double(x2);
      }
    print(sqrt(num:2))
    
    **output**
    1.414
    
    
      [1]: https://i.stack.imgur.com/SuLPj.png
    

提交回复
热议问题