-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.swift
61 lines (58 loc) · 1.82 KB
/
main.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// return the result of the calculator.
func calculate(num1: Float, num2: Float, op: String) -> Float {
var result: Float = 0
switch op {
case "+":
result = num1 + num2
case "-":
result = num1 - num2
case "*":
result = num1 * num2
case "/":
result = num1 / num2
default:
result = 0
}
return result
}
var operatorInput: String = ""
func operatorInputfunc() -> String {
repeat {
// ask what operator to be inputted
print("What operator do you want to use?")
operatorInput = readLine()!
// while the operator input is not +, -, *, / throw an error
if operatorInput != "+" && operatorInput != "-" &&
operatorInput != "*" && operatorInput != "/" {
print("Please input a valid operator.")
}
// if operatorInput is q
if operatorInput == "q" {
break
}
} while operatorInput != "+" && operatorInput != "-" &&
operatorInput != "*" && operatorInput != "/"
return operatorInput
}
repeat {
// call the operatorInputfunc function
operatorInput = operatorInputfunc()
// if operatorInput is q
if operatorInput == "q" {
print("Goodbye!")
break
}
// get the float num1 and float num2
print("Enter the first number:")
let num1 = Float(readLine()!)!
print("Enter the second number:")
let num2 = Float(readLine()!)!
// if op is == / and num2 is equal to 0 then throw error
if operatorInput == "/" && num2 == 0 {
print("You cannot divide by 0.")
}
// calculate the result
let res = calculate(num1: num1, num2: num2, op: operatorInput)
// print and format the result
print("\(num1) \(operatorInput) \(num2) = \(res)")
} while operatorInput != "q"