gpt4 book ai didi

arrays - Fixnum与nil的比较失败-回文程序Ruby

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

我正在为欧拉计划中的第 4 题编写程序 - 在 3 位数的倍数中找到最大的回文。这是我写的:

def palintest(number)
num = number.to_s
len = num.length

if len % 2 != 0
num[(len/2).floor] = ''
end

if num[0.. (len/2)-1] == num [len/2..len].reverse!
return number
end
end

palindromes = []

for i in 100..999
for j in 100..999
palindromes << palintest(i*j)
end
end

puts palindromes.max

我收到一条错误消息:

comparison of Fixnum with nil failed
(repl):24:in `each'
(repl):24:in `max'
(repl):24:in `initialize'

我无法真正弄清楚发生了什么,我已经测试了程序的每个组件并且它似乎处于工作状态。任何帮助将不胜感激。

最佳答案

乍一看,这是因为当 i*j 不是回文时,palintest(i*j) 返回 nil。

快速修复:

puts palindromes.reject(&:nil?).max

关于arrays - Fixnum与nil的比较失败-回文程序Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720845/

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