所以我写了一个用Ruby做模除的程序,使用了一个模块:
module Moddiv
def Moddiv.testfor(op1, op2)
return op1 % op2
end
end程序:
require 'mdivmod'
print("Enter the first number: ")
gets
chomp
firstnum = $_
print("Enter the second number: ")
gets
chomp
puts
secondnum = $_
puts "The remainder of 70/6 is " + Moddiv.testfor(firstnum,secondnum).to_s当我用两个数字运行它时,比如70和6,我得到70作为输出!为什么会发生这种情况?
发布于 2012-03-22 00:16:51
这是因为firstnum和secondnum是字符串"70"和"6"。并且定义了String#% -它是格式化输出操作符。
由于"70"不是格式化字符串,因此它被视为文字;因此"70" % "6"根据模板"70" (即"70" )打印格式化的"6“。
你需要用firstnum = $_.to_i等来转换你的输入。
发布于 2012-03-22 00:17:13
Modulo似乎在字符串方面遇到了问题,例如,在irb中:
"70" % "6" => "70"尝试执行您的return语句:
return op1.to_i % op2.to_i发布于 2012-03-22 00:17:06
您获取的用户输入是字符串,而不是整数。
"70" % "6"
# => "70"
70 % 6
# => 4在您的参数上使用.to_i,您就可以开始工作了。
https://stackoverflow.com/questions/9808357
复制相似问题