忘れないようにメモ
はじめに
下記のような変数があったとする
var low = 0
var high = 3
これと
Int(ceil(Double((low + high) / 2)))
これ
Int(ceil(Double(low + high) / 2))
当たり前だが、計算結果が違う
playgroundで実行してみる
import Foundation
var low = 0
var high = 3
print(Int(ceil(Double((low + high) / 2))))
// 1と出力
print(Int(ceil(Double(low + high) / 2)))
// 2と出力
それぞれ分解してみる
print("low + high: ",low + high)
print("(low + high) / 2 :", (low + high) / 2)
print("Double((low + high) / 2)) :",Double((low + high) / 2) )
print("ceil(Double((low + high) / 2)) : ", ceil(Double((low + high) / 2)))
print("Int(ceil(Double((low + high) / 2))) : ",Int(ceil(Double((low + high) / 2))))
low + high: 3
(low + high) / 2 : 1
Double((low + high) / 2)) : 1.0
ceil(Double((low + high) / 2)) : 1.0
Int(ceil(Double((low + high) / 2))) : 1
print("low + high: ",low + high)
print("Double(low + high) : ", Double(low + high))
print("Double(low + high) / 2 :", Double(low + high) / 2)
print("ceil(Double(low + high) / 2) :",ceil(Double(low + high) / 2))
print("Int(ceil(Double(low + high) / 2)) : ", Int(ceil(Double(low + high) / 2)))
low + high: 3
Double(low + high) : 3.0
Double(low + high) / 2 : 1.5
ceil(Double(low + high) / 2) : 2.0
Int(ceil(Double(low + high) / 2)) : 2
Double
に型を変換するタイミングを間違えて時間をくってしまったのだが、おちついて考えるとまあそうですよね・・・という気持ちになる