forked from Ada-C10/calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.rb
98 lines (86 loc) · 2.3 KB
/
calculator.rb
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
95
96
97
98
# create methods for calculations
def multiply(num1, num2)
answer = num1.to_i * num2.to_i
puts "#{num1} * #{num2} = #{answer}"
return answer
end
def add(num1, num2)
answer = num1.to_i + num2.to_i
puts "#{num1} + #{num2} = #{answer}"
return answer
end
def subtract(num1, num2)
answer = num1.to_i - num2.to_i
puts "#{num1} - #{num2} = #{answer}"
return answer
end
def divide(num1, num2)
if num2.to_i == 0
answer = "Undefined"
else
answer = num1.to_f / num2.to_f
end
puts "#{num1} / #{num2} = #{answer}"
return answer
end
def exponent(num1, num2)
answer = num1.to_i ** num2.to_i
puts "#{num1} ^ #{num2} = #{answer}"
return answer
end
def modulo(num1, num2)
if num2.to_i == 0
answer = "Undefined"
else
answer = num1.to_i % num2.to_i
end
puts "#{num1} % #{num2} = #{answer}"
return answer
end
puts "Welcome to the Calculator program! Which operator would you like to use?"
puts "1. add (+)"
puts "2. subtract (-)"
puts "3. multiply (*)"
puts "4. divide (/)"
puts "5. exponent (^)"
puts "5. modulo (%)"
puts "Please choose one operator (name or symbol): "
# make sure operator is a valid option
operator = gets.chomp
until ["add", "+", "subtract", "-", "multiply", "*", "divide", "/", "exponent", "^", "modulo", "%"].include?(operator)
puts "Please select a valid operator:"
operator = gets.chomp
end
puts "Please input integers you would like to calculate:"
# get first integer
puts "First integer: "
first_number = gets.chomp
until first_number.to_i.to_s == first_number
puts "That's not an integer! Please input an integer:"
first_number = gets.chomp
end
# get second integer
puts "Second integer: "
second_number = gets.chomp
until second_number.to_i.to_s == second_number
puts "That's not an integer! Please input an integer:"
second_number = gets.chomp
end
# depending on operator, invoke correct calculation method
case operator
when "add", "+"
add(first_number, second_number)
when "subtract", "-"
subtract(first_number, second_number)
when "multiply", "*"
multiply(first_number, second_number)
when "divide", "/"
divide(first_number, second_number)
when "exponent", "^"
exponent(first_number, second_number)
when "modulo", "%"
modulo(first_number, second_number)
else
puts "Yikes something went wrong :( "
end
puts "Thanks for using the Calculator program!"