Ruby Modulo部门 [英] Ruby Modulo Division
问题描述
所以我制作了一个程序,使用模块在Ruby中进行模除:
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
程序:
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作为输出!为什么会这样?
When I run it with two numbers, say 70 and 6, I get 70 as the output! Why is this happening?
推荐答案
这是因为firstnum
和secondnum
是字符串 "70"
和"6"
.并定义了String#%
-它是格式化输出运算符.
It's because firstnum
and secondnum
are the strings "70"
and "6"
. And String#%
is defined - it's the formatted-output operator.
由于"70"
不是格式字符串,因此将其视为文字.因此"70" % "6"
打印根据模板"70"
格式化的"6",该模板就是"70"
.
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"
.
您需要使用firstnum = $_.to_i
等转换输入.
You need to convert your input with firstnum = $_.to_i
etc.
这篇关于Ruby Modulo部门的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!