RangeError:bignum太大而无法转换成`long’
num = "0000001000000000011000000000000010010011000011110000000000000000" for n in 0...num.length temp = num[n] dec = dec + temp*(2**(num.length - n - 1)) end puts dec
当我在irb中运行此代码时,以下错误消息是输出。 当我在python中编译相同的逻辑时,它工作得非常好。 我用谷歌搜索了“RangeError:bignum太大而无法转换为’long’:但没有找到相关的答案。请帮帮我:(先谢谢你。
RangeError:bignum太大而无法转换为long' from (irb):4:in
long' from (irb):4:in
long' from (irb):4:in
*' from(irb):4:in inblock in irb_binding' from (irb):2:in
block in irb_binding' from (irb):2:in
block in irb_binding' from (irb):2:in
每个' 来自(irb):2 来自C:/ Ruby193 / bin / irb:12:in''
试试这个
num = "0000001000000000011000000000000010010011000011110000000000000000" dec = 0 for n in 0...num.length temp = num[n] dec = dec + temp.to_i * (2**(num.length - n - 1)) end puts dec
num[n]
得到的是一个字符串,而不是一个数字。 我把你的代码改写成更惯用的Ruby,这就是它的样子:
dec = num.each_char.with_index.inject(0) do |d, (temp, n)| d + temp.to_i * (2 ** (num.length - n - 1)) end
然而,最惯用的可能是num.to_i(2)
,因为正如我所看到的那样,你正试图从二进制转换为十进制,这正是它的作用。