I have a question


#1

I have a question. I made this Ruby code (below) but it doesn’t work (there are no errors). You can put numbers in (gets.chomp) but the code doesn’t give an output.
Can someone tell me what is the error?
This is the code:

puts "Calculator!"
number_one = gets.chomp
thing = gets.chomp
number_two = gets.chomp
def calculate
if thing == "+"
puts number_one + number_two
elsif thing == "-"
puts number_one - number_two
elsif thing == "*"
puts number_one * number_two
elsif thing == "/"
puts number_one / number_two
elsif thing == "**"
puts number_one ** number_two
else
puts "Error. Try again."
calculate
end
end
def question
puts "Again? (type ‘yes’ or ‘no’)"
choice = gets.chomp
if choice == "yes"
calculate
elsif choice == "no"
puts "Bye!"
else
puts "Error. Ask again."
question
end
end


#2

Could you fix the formatting of your post so that others can copy and run your code?
Additionally, what input are you giving it, what does it look like when you run it, and what did you expect it to look like instead?

Anyway, if squinting really hard and trying to read that block of text (of code that is probably not exactly what you’re running due to different formatting)
Then, one can tell that you do a total of 6 things: 1) print Calculator 2) read input 3) read input 4) read input 5) create function 6) create function

that’s it, after that the program is done. Note that I didn’t encounter anything doing output aside from 1) – so where should program execution have gone different? You’ll probably need to add some code which does that, there

I might have gotten a bad copy (because it’s copied from your post and then edited), but the code should look roughly like this when viewing it:
Now it’s not just a block of text, it’s possible to see that there are two functions and 4 other lines, and that nothing else is happening

puts "Calculator!"
number_one = gets.chomp
thing = gets.chomp
number_two = gets.chomp

def calculate
  if thing == "+"
    puts number_one + number_two
  elsif thing == "-"
    puts number_one - number_two
  elsif thing == "*"
    puts number_one * number_two
  elsif thing == "/"
    puts number_one / number_two
  elsif thing == "**"
    puts number_one ** number_two
  else
    puts "Error. Try again."
    calculate
  end
end

def question
  puts "Again? (type 'yes' or 'no')"
  choice = gets.chomp
  if choice == "yes"
    calculate
  elsif choice == "no"
    puts "Bye!"
  else
    puts "Error. Ask again."
    question
  end
end

#3

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