-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.rb
72 lines (61 loc) · 2.03 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
puts "Enter your first number"
num1= gets.chomp.to_f
puts "Enter your operation"
operation = gets.chomp
puts "Enter your second number"
num2 = gets.chomp.to_f
answer = 0
def addition(num1, num2)
return num1 + num2
#num1 = answer
end
def subtraction(num1, num2)
return num1 - num2
end
def multiplication(num1, num2)
#answer = num1 * num2 #any changes made to the variables within the method definition is local and cannot be seen outside of the method definition so I'm not changing the value of answer at the top of the program
#num1 = answer
return num1 * num2
end
def division(num1, num2)
return num1 / num2
#num1 = answer
end
while operation != "=" do
if operation == "+"
#puts "before #{num1} #{num2} #{answer}"
answer = addition(num1, num2) #within the while loop, changing the values of answer and num1 changes the values of answer and num1 at the top of the program - that's good bc when I pass the variables to the methods, the num1 and answer variables maintain their values assigned in here, in the while loop bc the variables' values (num1 and answer are defined at the top of the program) were reassigned here in the while loop
num1 = answer
#puts "after #{num1} #{num2} #{answer}"
elsif operation == "-"
answer = subtraction(num1, num2)
num1 = answer
elsif operation == "/"
answer = division(num1, num2)
num1 = answer
elsif operation == "*"
answer = multiplication(num1, num2)
num1 = answer
else
puts "Please enter +, -, / or *"
end
puts "Enter your operation"
#if gets.chomp == "=" || gets.chomp == "+" || gets.chomp == "-" || gets.chomp == "/" || gets.chomp == "*"
operation = gets.chomp
#else
# puts "Error: enter =, +, -, / or *"
#break
#end
if operation != "="
puts "Enter a number"
# if gets.chomp.include?(/\D/)
# puts "Error: enter a number next time"
# break
# else
num2 = gets.chomp.to_f
# end
else
puts "Your answer is #{answer}"
break
end
end