【发布时间】:2015-12-15 00:39:05
【问题描述】:
当我试图为我的代码创建一个循环时,它突然问我这个:
main:Object (NameError) 的未定义局部变量或方法“停止”。
如何解决此错误?
loop do
puts "Hello. I am a calculator. Please tell me your name."
name = gets
puts "Hi #{name}. Enter 1 to add, 2 to multiply, 3 to subtract, and 4 to divide."
z = gets.chomp.to_i
def addition
puts "Please enter your first number"
a = gets.chomp.to_i
puts "Please enter your second number"
b = gets.chomp.to_i
puts a+b
end
def multiply
puts "Please enter your first number"
c = gets.chomp.to_i
puts "Please enter your second number"
d = gets.chomp.to_i
puts c*d
end
def subtract
puts "Please enter your first number"
e = gets.chomp.to_i
puts "Please enter your second number"
f = gets.chomp.to_i
puts e-f
end
def divide
puts "Please enter your first number"
h = gets.chomp.to_i
puts "Please enter your second number"
g = gets.chomp.to_i
puts h/g
end
if z == 1
puts addition
elsif z == 2
puts multiply
elsif z == 3
puts subtract
elsif z == 4
puts divide
end
puts "Would you like to calculate something else or stop?"
choice = gets.chomp.to_s
if choice == stop
break
end
end
【问题讨论】:
-
欢迎来到 Stack Overflow。请阅读您的问题,并想象您被同事问过同样的问题。你想看什么来帮助回答这个问题?将其添加到问题中。如果我们要为您提供任何详细的帮助,您的问题非常模糊,需要详细说明。
-
抱歉代码有点奇怪
-
停止应该是“停止”。如果您不将其括在引号中,系统会将其视为变量,这就是您收到该错误的原因。