2012-03-21 118 views
1

所以我做了一个程序做在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作为输出!这是为什么发生?

+0

sscce.org。另外,你确定这是一个关于Rails的问题吗?对我来说就像Ruby。 – 2012-03-21 16:07:28

+0

是的,它只是红宝石,我分心,键入导轨,而不是,编辑 – Billjk 2012-03-21 16:08:34

+1

尝试简化您的代码,并在这里发布整个事情。你可以将它简化为1行。 – 2012-03-21 16:10:24

回答

10

这是因为firstnumsecondnum"70""6"。并定义了String#% - 它是格式化输出运算符。

由于"70"不是格式字符串,所以它被视为文字;所以"70" % "6"打印“6”,根据模板"70"格式化,这只是"70"

您需要将输入转化与firstnum = $_.to_i

0

你抓住用户输入字符串,而不是整数。

"70" % "6" 
# => "70" 

70 % 6 
# => 4 

对你的参数使用.to_i,你应该很好去。

2

模似乎与字符串的麻烦,例如,在内部评级法:

"70" % "6" => "70" 

请尝试将return语句:

return op1.to_i % op2.to_i 
+0

@Chowlett有一个更好的解释(并打败我21秒!) – 2012-03-21 16:19:13