簡易運算子


標籤

算術運算子

運算子 運算
餘數
let x = 50, y = 20
print("\(x) + \(y) = \(x + y)")
print("\(x) - \(y) = \(x - y)")
print("\(x) * \(y) = \(x * y)")
print("\(x) / \(y) = \(x / y)")
print("\(x) % \(y) = \(x % y)")
let x = Float(50), y = Float(20)
print("\(x) / \(y) = \(x / y)")
let x = Double(50), y = Double(20)
print("\(x) / \(y) = \(x / y)")
  • 輸出結果
    50 + 20 = 70
    50 - 20 = 30
    50 * 20 = 1000
    50 / 20 = 2
    50 % 20 = 10
    50.0 / 20.0 = 2.5
    50.0 / 20.0 = 2.5
    
    • 附註:兩數相除需資料型態相同

指定運算子

運算子 比較
+=
-=
*=
/=
%= 餘數
var number = 50
    number += 50
    print("\(number) += 50 = \(number)")
    number -= 50
    print("\(number) -= 50 = \(number)")
    number *= 2
    print("\(number) *= 2 = \(number)")
    number /= 2
    print("\(number) /= 2 = \(number)")
    number %= 40
    print("\(number) %= 40 = \(number)")
  • 輸出結果
    50 += 50 = 100
    50 -= 50 = 0
    50 *= 2 = 100
    50 /= 2 = 25
    50 % 40 = 10
    

關系運算子

運算子 比較
大於
>= 大於等於
小於
<= 小於等於
== 等於
!= 不等於
let x = 50, y = 20
print("\(x) > \(y) = \(x > y)")
print("\(x) >= \(y) = \(x >= y)")
print("\(x) < \(y) = \(x < y)")
print("\(x) <= \(y) = \(x <= y)")
print("\(x) == \(y) = \(x == y)")
print("\(x) != \(y) = \(x != y)")
  • 輸出結果
    50 > 20 = true
    50 >= 20 = true
    50 < 20 = false
    50 <= 20 = false
    50 == 20 = false
    50 != 20 = false
    

邏輯運算子

運算子 邏輯
&& 大於
|| 大於等於
小於
let x = 50, y = 20
let andValue: Bool = x == 50 && y != 20
print("\(x) == 50 && \(y) != 20 = \(andValue)")
let orValue: Bool = x == 50 || y != 20
print("\(x) == 50 || \(y) != 20 = \(orValue)")
let notValue: Bool = !(x == 50)
print("!(\(x) == 50) = \(notValue)")
  • 輸出結果
    50 == 50 && 20 != 20 = false
    50 == 50 || 20 != 20 = true
    !(50 == 50) = false
    

運算子優先順序

運算子
*  /  %
+  - 
>  >=  <  <=
==  !=
&&
||
=  +=  -=  *=  /=  %=

results matching ""

    No results matching ""