gpt4 book ai didi

Ruby 模除法

转载 作者:数据小太阳 更新时间:2023-10-29 08:16:02 24 4
gpt4 key购买 nike

所以我用一个模块在 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 作为输出!为什么会这样?

最佳答案

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

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

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

关于Ruby 模除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9808357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com