gpt4 book ai didi

ruby - 为什么从文件读取时需要 `to_s` 在 `to_i` 之上?

转载 作者:数据小太阳 更新时间:2023-10-29 07:14:10 30 4
gpt4 key购买 nike

我从文件中读取了一个数字 "98",并尝试使用 input.to_i(2) 将其转换为二进制,但我得到了 0 这样。

input=File.read("input.dat")
puts "Input is: #{input}"
puts "Normal way is #{input.to_i(2)}"
puts "It works this way #{input.to_i.to_s(2)}"
puts "Calling the number directly works #{98.to_s(2)}"

输出是:

Input is: 98
Normal way is 0
It works this way 1100010
Calling the number directly works 1100010

最佳答案

to_i(2) 将字符串中的表达式解释为二进制数,它应该只包含"0""1"。由于 "98" 无效,因此在设计上默认结果变为 0。 (它本来可以被设计成返回 nil 或引发错误,但不知何故它是这样设计的。)

要将数字显示为二进制,您需要 to_s(2),因为它给出了数字的二进制表达式。

作为数字,没有二进制数、十进制数等之分,只有一个数。那些二进制、十进制等概念是关于它们表示为字符串的方式。

关于ruby - 为什么从文件读取时需要 `to_s` 在 `to_i` 之上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793747/

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