Ruby Modulo Division

Bil*_*ljk 2 ruby modulo

所以我创建了一个程序,使用模块在Ruby中进行模数除法:

module Moddiv
    def Moddiv.testfor(op1, op2)
        return op1 % op2
    end
end
Run Code Online (Sandbox Code Playgroud)

程序:

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
Run Code Online (Sandbox Code Playgroud)

当我使用两个数字运行它时,比如70和6,我得到70作为输出!为什么会这样?

Cho*_*ett 10

这是因为firstnum并且secondnum字符串 "70""6".并且String#%已定义 - 它是格式化输出运算符.

因为"70"它不是格式字符串,所以它被视为文字; 所以"70" % "6"打印"6"根据模板格式化"70",这是正确的"70".

您需要转换输入firstnum = $_.to_i等.