LoginSignup
0
3

More than 5 years have passed since last update.

Swift 計算の順番を間違えて詰まったのでメモ

Posted at

忘れないようにメモ

はじめに

下記のような変数があったとする

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に型を変換するタイミングを間違えて時間をくってしまったのだが、おちついて考えるとまあそうですよね・・・という気持ちになる

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3