-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.kt
94 lines (81 loc) · 2.73 KB
/
calculator.kt
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.Scanner
import kotlin.math.sqrt
import kotlin.math.pow
fun main() {
val scanner = Scanner(System.`in`)
var result = 0.0
var continueCalculation = true
val history = mutableListOf<String>()
println("\n")
println("...Welcome to Kotlin Calculator...")
while (continueCalculation) {
if (result == 0.0) {
println("Enter first number:")
result = scanner.nextDouble()
}
println("Enter operator (+, -, *, /, sqrt, ^, c, h) or '=' to finish:")
val operator = scanner.next()
when (operator) {
"=" -> {
continueCalculation = false
break
}
"c" -> {
result = 0.0
println("Result cleared. Start a new calculation.")
continue
}
"h" -> {
println("Calculation history:")
if (history.isEmpty()) {
println("No calculations yet.")
} else {
history.forEach { println(it) }
}
continue
}
"sqrt" -> {
val previousResult = result
result = sqrt(result)
history.add("sqrt($previousResult) = $result")
println("Current result: $result")
continue
}
else -> if (!isValidOperator(operator)) {
println("Invalid operator. Please enter a valid operator.")
continue
}
}
println("Enter next number:")
val num2 = scanner.nextDouble()
val previousResult = result
when (operator) {
"+" -> result += num2
"-" -> result -= num2
"*" -> result *= num2
"/" -> {
if (num2 != 0.0) {
result /= num2
} else {
println("Error: Division by zero")
continue
}
}
"^" -> result = result.pow(num2)
}
history.add("$previousResult $operator $num2 = $result")
println("Current result: $result")
}
println("Final result: $result")
println("Would you like to see the calculation history? (Y/N)")
val showHistory = scanner.next()
if (showHistory.equals("Y", ignoreCase = true)) {
println("Calculation history:")
history.forEach { println(it) }
}
println("Calculator program closed.")
scanner.close()
}
fun isValidOperator(operator: String): Boolean {
return operator in setOf("+", "-", "*", "/", "^")
}