Ruby Modulo Division

為{幸葍}努か 提交于 2019-12-12 21:21:42

问题


So I made a program to do modulo division in Ruby, using a module:

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

When I run it with two numbers, say 70 and 6, I get 70 as the output! Why is this happening?


回答1:


It's because firstnum and secondnum are the strings "70" and "6". And String#% is defined - it's the formatted-output operator.

Since "70" is not a format string, it's treated as a literal; so "70" % "6" prints "6" formatted according to the template "70", which is just "70".

You need to convert your input with firstnum = $_.to_i etc.




回答2:


Modulo seems to have trouble with strings, for example, in irb:

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

try making your return statement:

return op1.to_i % op2.to_i



回答3:


You're grabbing user input as strings, not integers.

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

70 % 6
# => 4

Use .to_i on your parameters and you should be good to go.



来源:https://stackoverflow.com/questions/9808357/ruby-modulo-division

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!