Simple calculator to add, subtract, multiply or divide


#1

Trying to create a simple program that will take two numbers then gives the user a choice of what kind of arithmetic they’d like done to the two numbers to Include at least: add, subtract, multiply and divide.


#2

Is this a homework assignment or a Ruby lesson?

Inline code
def enter(a, b, op)
  case op
  when "+"
    a + b
  when "-"
    a - b
  when "*"
    a * b
  when "/"
    a / b
  end
end

print "Enter A: "
a = gets.chomp
a = a.to_f
print "Enter B: "
b = gets.chomp
b = b.to_f
op = ""
until ["+", "-" ,"*", "/"].include?(op) do
  print "Operator [ + | - | * | / ]: "
  op = gets.chomp
end

puts "#{a} #{op} #{b} = #{enter(a, b, op)}"
Enter A:  6
Enter B:  7
Operator [ + | - | * | / ]:  *
6.0 * 7.0 = 42.0
functional approach
# http://mentalized.net/journal/2011/04/14/ruby-how-to-check-if-a-string-is-numeric/
class String
  def numeric?
    Float(self) != nil rescue false
  end
end
####
def get_number(r="a number", x="")
  until x.numeric?
    print "Enter #{r}: "
    x = gets.chomp
  end
  x.to_f - x.to_i != 0 ? x.to_f : x.to_i
end

def get_operator(operator="")
  until ["+", "-", "*", "/"].include?(operator) do
    print "Operator [ + | - | * | / ]: "
    operator = gets.chomp
  end
  operator
end

def enter(a, b, operator)
  case operator
  when "+" then a + b
  when "-" then a - b
  when "*" then a * b
  when "/" then a / b
  end
end
a = get_number('A')
b = get_number('B')
op = get_operator()
puts "#{a} #{op} #{b} = #{enter(a, b, op)}"
Enter A:  6
Enter B:  7
Operator [ + | - | * | / ]:  *
6 * 7 = 42
Enter A:  3.14
Enter B:  4
Operator [ + | - | * | / ]:  *
3.14 * 4 = 12.56

#3

#4

both homework and lesson


#5

Whatever you do, don’t use the above code. The teacher will know it’s not yours. Use only code patterns and techniques learned so far in the course.

Do please show us what you have so far composed.


Edit

Or not. Going to unlist this topic since it does not appear to matter whether teacher sees it or not. Til now we were in protective mode.


#6

#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.