Swift 3 - 查找数字是否是完美的正方形

时间:2017-04-09 00:54:45

标签: swift perfect-square

我想知道是否有办法找到一个数字是否是Swift中的完美正方形。我让用户输入一个数字来检查它是否是一个完美的正方形。有声明或功能吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

var number = 9.0

let root = sqrt(number)
let isInteger = floor(root) == root
print("\(root) is \(isInteger ? "perfect" : "not perfect")")

那" isInteger"我找到了in this related question

答案 1 :(得分:1)

您可以将整数转换为double并获取其squareRoot属性,将其四舍五入并与其squareRoot进行比较:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let location = (touches.first)?.location(in: self.view) 
        if (location?.x)! < (self.view?.bounds.size.width)!/2 {
            player1.run(SKAction.moveTo(x: 0 + player1.size.width / 2, duration: 0.1))
            player2.run(SKAction.moveTo(x: 0 + player1.size.width + player2.size.width / 2, duration: 0.1)) 
        } else {
            player1.run(SKAction.moveTo(x: self.frame.width - player1.size.width - player2.size.width / 2, duration: 0.1))
            player2.run(SKAction.moveTo(x: self.frame.width - player1.size.width / 2, duration: 0.1))
        }
    }

<强>游乐场

extension Integer {
    var double: Double { return Double(toIntMax()) }
    var isPerfectSquare: Bool {
        return double.squareRoot().rounded() == double.squareRoot()
    }
}