这是我的第一种编程语言,所以请耐心等待我!
我无法弄清楚哪里出错了。我不一定要求解决方案,因为这是一个学习练习;我只是需要帮助我应该在哪里寻找。
#Calculate the sum of two numbers and an optional third
#get first number
print "Please enter your first digit: "
value_1 = gets.chomp
print value_1
#get second number
print "Please enter your second digit: "
value_2 = gets.chomp
#get the additional number
print "Do you want to add an additional number?"
add_num_req = gets.chomp
#calculate result and put
if gets.chomp = "yes" || "Yes" || "YES"
print "Please enter the additional digit: "
add_num_1 = gets.chomp
#print sum of three values
print "Answer: " , (value_1.to_i + value_2.to_i + add_num_1.to_i), "\n";
else
#print value_1 + value_2
print "Answer: " , (value_1.to_i + value_2.to_i), "\n";
end
但是在对get.chomp
作出额外数字的回复之后,这会产生一个空白回报。有什么帮助吗?
答案 0 :(得分:2)
作为第四种选择(以及我通常使用的)......
if gets.chomp.downcase == "yes"
与正则表达式匹配一样,它也接受意外的案件安排(例如“yEs”,“yES”,“YeS”等)
答案 1 :(得分:1)
在Ruby中,您可以将变量与许多选项进行比较。你必须做这样的事情:
if add_num_req == "yes" || add_num_req == "Yes" || add_num_req == "YES"
另一种方法是利用Enumerable模块。但这有点先进,虽然你会发现它在继续使用Ruby时很有用。
answers = ["yes", "Yes", "YES"]
if answers.any? { |e| add_num_req == e }
答案 2 :(得分:0)
变化:
if gets.chomp = "yes" || "Yes" || "YES" #you are using = instead of == which is equality
为:
if gets.chomp.match(/yes/i) #This is a case-insensitive regex to match "yes", "Yes" or "YES"
答案 3 :(得分:0)
第三种选择:
if ( ['yes','Yes','YES'].include?(add_num_req) )
...
答案 4 :(得分:0)
这是一种类似Ruby的编写程序的方式:
def doit
value_1 = obtain_entry("Please enter your first digit: ").to_i
value_2 = obtain_entry("Please enter your second digit: ").to_i
loop do
case obtain_entry("Do you want to add an additional digit?: ")
when "yes", "Yes", "YES"
print "Please enter the additional digit: "
puts "Answer: #{value_1 + value_2 + gets.to_i}"
break
when "no", "No", "NO"
puts "Answer: #{value_1 + value_2}"
break
end
end
end
def obtain_entry(str)
print str
gets.chomp
end
doit
几点:
obtain_entry
)。对于要被视为整数的答案,您可以在返回时将它们转换为整数。 (在实际应用中,您当然希望对答案的类型和合理性进行各种检查。)"Do you want to add an additional digit?: "
和"Please enter the additional digit: "
创建变量。"Do you want to add an additional digit?
。如果给出了可接受的答案,我们就会摆脱循环;如果没有,则重复该问题,并给予用户另一个回答的机会。case
语句通常很方便。#{variable_x}
),就像在puts "Answer: #{value_1 + value_2 + gets.to_i}"
中一样,使用了更传统的字符串形式。您必须使用 double 引号进行字符串插值才能正常工作。gets.to_i
就足够了。答案 5 :(得分:0)
我的猜测是你的问题发生在这里:
#get the additional number
print "Do you want to add an additional number?"
add_num_req = gets.chomp
#calculate result and put
if gets.chomp = "yes" || "Yes" || "YES"
由于您为同一输入调用gets.chomp
两次,并使用赋值运算符=
代替比较运算符==
。此外,正如其他人指出的那样,每个||
运算符都应该评估布尔表达式,例如: add_num_req == 'yes' || add_num_req == 'YES'
。如果不修改你的代码太多,我想你想要这样的东西:
print "Do you want to add an additional number? "
add_num_req = gets.chomp
#calculate results and put
if add_num_req.downcase == 'yes'
# ...
在这方面,如果你计划评估很多字符串,正则表达式是非常宝贵的。我仍然无法在不检查引用的情况下编写正确的正则表达式,但即便如此,它们也会让世界变得与众不同!