所以我用一个模块编写了一个在 Ruby 中进行模除法的程序:
module Moddiv
def Moddiv.testfor(op1, op2)
return op1 % op2
end
end
Program:
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 作为输出!为什么会发生这种情况?
这是因为firstnum
and secondnum
是strings "70"
and "6"
. And String#%
已定义 - 它是格式化输出运算符。
Since "70"
不是格式字符串,它被视为文字;所以"70" % "6"
根据模板打印“6”格式"70"
,这只是"70"
.
您需要将您的输入转换为firstnum = $_.to_i
etc.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)