forked from Ada-C9/Calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.rb
More file actions
99 lines (82 loc) · 2.21 KB
/
calculator.rb
File metadata and controls
99 lines (82 loc) · 2.21 KB
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
99
# This is a calculator program
# the user should ask what they would like to calculate.
operations = ["multiply", "divide", "subtract", "exponify",
"modulate", "-", "*", "/", "**", "+", "%"]
puts "\nWelcome to your Calculator Program!"
puts "Enter two numbers and an operation."
puts "Would you like to continue? (yes/no) "
answer = gets.chomp.downcase
while answer == "yes" do
# first number
print "\n#1 Number: "
until (num_1 = gets.chomp) =~ /^\d*\.?\d+$/
#starting of line, any digit(zero or more), including periods, following any digit(zero or more), ending of string.
puts "\nInvalid input. Please enter a number: "
end
num_1 = num_1.to_f
# second number
print "\n#2 Number: "
until (num_2 = gets.chomp) =~ /^\d*\.?\d+$/
puts "\nInvalid input. Please enter a number: "
end
num_2 = num_2.to_f
# operation to perform
print "\nOperation: "
op = gets.chomp.downcase
until operations.include?("#{op}")
print "\nPlease enter an operation
(add, subtract, multiply, divide, exponify, or modulate): "
op = gets.chomp.downcase
end
# divide
def divide(num1, num2)
if num2 != 0
print "#{num1} / #{num2} = "
(num1 / num2).round(2)
else
puts "Can't divide by zero!"
end
end
# multiply
def multiply(num1, num2)
print "#{num1} * #{num2} = "
(num1 * num2).round(2)
end
# subtract
def subtract(num1, num2)
print "#{num1} - #{num2} = "
(num1 - num2).round(2)
end
# addition
def add(num1, num2)
print "#{num1} + #{num2} = "
(num1 + num2).round(2)
end
# exponify
def exponify(num1, num2)
print "#{num1} ^ #{num2} = "
(num1**num2).round(2)
end
# modulo
def modulate(num1, num2)
print "#{num1} % #{num2} = "
(num1%num2).round(2)
end
# print the result and round numbers by two decimals
case op
when "add", "+"
print add(num_1, num_2)
when "subtract", "-"
print subtract(num_1, num_2)
when "multiply", "*"
print multiply(num_1, num_2)
when "divide", "/"
print divide(num_1, num_2)
when "exponify", "**"
print exponify(num_1, num_2)
when "modulate", "%"
print modulate(num_1, num_2)
end
print "\nWould you like to continue? (yes/no) "
answer = gets.chomp.downcase
end