gpt4 book ai didi

ruby - 返回结果和取模的方法

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

我正在尝试编写一个方法,它要求两个 2 整数,并将第一个除以第二个并返回包括余数在内的结果。

def remainder(a,b)
return a/b
return a%b
end
puts remainder(100,6)

这就出来了

16

如果我使用这段代码

def remainder(a,b)
return a%b
end
puts remainder(100,6)

这就出来了

4

我不明白如何在 puts 语句中同时显示模值和余数。

更新根据 Simple Lime 的建议,我使用了以下代码...

def remainder(a,b)
return a.divmod(b)
end
puts remainder(100,6)

哪个放

16
4

并且如我所愿地运作。

最佳答案

当你需要返回多个值时,你可以从方法中返回一个数组:

def remainder(a, b)
[a / b, a % b]
end

puts remainder(100, 6).inspect # => [16, 4]

然后如果需要,您可以将每个值分配给不同的变量:

div, mod = remainder(100, 6)
puts div # => 16
puts mod # => 4

附带说明一下,如果您只需要 2 个数的商和模,已经有一个内置函数 divmod这样做,使用上面的技术:

100.divmod(6) # => [16, 4]

关于ruby - 返回结果和取模的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334715/

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