Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions calculator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@

# Program for calculator.
puts " Welcome to the calculator "
operators_array = %w[add + subtract - divide / multiply * % ^]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

puts operators_array

# To verify whether the user enteres a valid operator
puts "Which operation would you like to perform "
operation = gets.chomp
while !operators_array.include?(operation)
print "Invalid input,Please try again\n"
operation = gets.chomp
end

# To know when it needs to return an _integer_ versus a _float_.
def convert_i_f(value)
if (value =~ /\./)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This checks to see it if has ANY decimals in it. So the user could enter two of them, more detection of an invalid value would be better.

For example 3...1 is accepted

value = value.to_f
elsif
value = value.to_i
end
return value
end

# To check whether the user input is numeric for first number
flag = true
while flag
puts "Enter the first number "
num1 = gets.chomp
if (num1 =~ /[a-zA-Z]/)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only checks for letters (a-z), not punctuation for example.

print "Invalid input; Please input again\n"
else
flag = false
end
end
f_num = convert_i_f(num1)

# To check whether the user input is numeric for second number
flag = true
flag = true
while flag

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

notice how this section is a repeat of above... great candidate for a method!

puts "Enter the second number "
num2 = gets.chomp
if (num2 =~ /[a-zA-Z]/)
print "Invalid input; Please input again\n"
else
flag = false
end
end

s_num = convert_i_f(num2)

# To handle division by zero
while (s_num == 0 ) && (operation == "division" || operation == "/")
puts " Can't divide by Zero,Enter the input again "
num2 = gets.chomp
s_num = convert_i_f(num2)
end

# To perform the operations

if operation == "add" || operation == "+"
result = f_num + s_num
elsif operation == "subtract" || operation == "-"
result = f_num - s_num
elsif operation == "multiply" || operation == "*"
result = f_num * s_num
elsif operation == "division" ||operation == "/"
result = f_num/s_num
elsif operation == "modulo" || operation == "%"
result = f_num % s_num
elsif operation == "^"
result = f_num**s_num
end
puts "#{num1} #{operation} #{num2} = #{result}"