forked from Ada-C8/Calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator2.rb
67 lines (61 loc) · 1.95 KB
/
calculator2.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
# Method checks if user input is a whole number.
def number_check(num)
until num.is_a?(Integer) do
puts "Please input a whole number."
num = Integer(gets.chomp) rescue nil
end
return num
end
#Method checks if operator is valid.
def operator_check(sign)
until sign == "+" or sign == "add" or sign == "-" or
sign == "subtract" or sign == "*" or sign == "multiply" or
sign == "/" or sign == "divide" or sign == "^" or
sign == "exponent" or sign == "**" or sign == "%" or
sign == "mod" do
puts "I don't recognize that function. Try again."
sign = gets.chomp.downcase rescue nil
end
return sign
end
#Method compares input to operations and outputs the equations.
def do_math (sign, num1, num2)
if sign == "+" or sign == "add"
answer = num1 + num2
puts "#{num1} + #{num2} =#{answer}"
elsif sign == "-" or sign == "subtract"
answer = num1 - num2
puts "#{num1} - #{num2} =#{answer}"
elsif sign == "*" or sign == "multiply"
answer = num1 * num2
puts "#{num1} * #{num2} =#{answer}"
elsif sign == "/" or sign == "divide"
if num2 == 0
puts "Division by zero is undefined."
else
answer = num1 / num2
puts "#{num1} / #{num2} =#{answer}"
end
elsif sign == "^" or sign =="exponent" or sign == "**"
answer = num1 ** num2
puts "#{num1} ** #{num2} =#{answer}"
elsif sign == "%" or sign == "mod"
answer = num1 % num2
puts "#{num1} % #{num2} =#{answer}"
else
puts "Something's wrong. Do it again!"
end
end
#App contains welcome message and user prompts.
puts "Welcome to the Calculator!"
puts
puts "What is your first number?"
first_num = Integer(gets.chomp) rescue nil
first_num = number_check(first_num)
puts "What is your second number?"
second_num = Integer(gets.chomp) rescue nil
second_num = number_check(second_num)
puts "what is your operator?"
operator = gets.chomp.downcase rescue nil
operator = operator_check(operator)
do_math(operator, first_num, second_num)