Ruby Modulo Division

所以我创建了一个程序,在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作为输出! 为什么会这样?

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

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

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

Modulo似乎在字符串方面有问题,例如,在irb中:

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

尝试制作你的退货声明:

 return op1.to_i % op2.to_i 

您将用户输入捕获为字符串,而不是整数。

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

在参数上使用.to_i ,你应该很高兴。