Arrays Ruby:为什么数组中的最后一个元素被更改为1?
我的函数将输入的二进制数转换为十进制等效数。但是,当我输入110而不是得到6时(Arrays Ruby:为什么数组中的最后一个元素被更改为1?,arrays,ruby,Arrays,Ruby,我的函数将输入的二进制数转换为十进制等效数。但是,当我输入110而不是得到6时([2^2*1,2^1*1,2^0*0]⇒ [4+2+0]⇒ 6)我得到7,因为数组中的最后一个值更改为1。([1,1,0]⇒ [1,1,1])。当我使用.to\ItovalueInt保存该索引处的值时,会发生这种情况。但是,同时有一个if语句,它应该阻止对其中包含0的元素执行任何操作。我被难住了 puts "BinaryArr: #{binaryArr}" # loops through the array in
[2^2*1,2^1*1,2^0*0]
⇒ <代码>[4+2+0]⇒ <代码>6)我得到7,因为数组中的最后一个值更改为1。([1,1,0]
⇒ <代码>[1,1,1])。当我使用.to\I
tovalueInt
保存该索引处的值时,会发生这种情况。但是,同时有一个if
语句,它应该阻止对其中包含0的元素执行任何操作。我被难住了
puts "BinaryArr: #{binaryArr}"
# loops through the array in reverse order and converts the 1's
# to their respective weight by location
binaryArr.reverse.each_index do |index|
if binaryArr[index] != 0 then
valueInt = binaryArr[index].to_i
puts "ValueInt: #{valueInt}"
val = (2**index)*valueInt
puts "val: #{val}"
binaryArr[(binaryArr.length - 1) - index] = "#{val}"
end
end
puts "WeightArr: #{binaryArr}"
# loops through the arr adding the elements together for the total (decimal value)
decimalInt = 0
binaryArr.each_index do |x|
thisVal = binaryArr[x].to_i
decimalInt += thisVal
if binaryArr[x + 1] == nil then
break
end
end
puts "Decimal Value: #{decimalInt}"
输出:输入110时
Binary is: 3 Bits long
BinaryArr: ["1", "1", "0"]
ValueInt: 1 <== why is this a 1 instead of a 0!?!?
val: 1
ValueInt: 1
val: 2
ValueInt: 1
val: 4
WeightArr: ["4", "2", "1"]
Decimal Value: 7
二进制为:3位长
二进制数组:[“1”、“1”、“0”]
参数:1
if binaryArr[index]=0,然后根据输出二进制arr
包含字符串。“a_字符串”!=0总是正确的
0**0
的结果为1
您正在对循环内的binaryArr
进行索引binaryArr.reverse。每个索引都执行
end
获取值valueInt
,但您应该为反向
建立索引。您可以在循环之前在变量中设置reverse
,如reverseArr=binaryArr.reverse
,并确保迭代reverseArr
,并在循环内对其编制索引。例如:
puts "BinaryArr: #{binaryArr}"
reverseArr = binaryArr.reverse
# lops through the array in reverse order and converts the 1's
# to there respective weight by location
reverseArr.each_index do |index|
valueInt = reverseArr[index].to_i
puts "ValueInt: #{valueInt}"
val = (2**index)*valueInt
puts "val: #{val}"
binaryArr[(binaryArr.length-1)-index] = "#{val}"
end
puts "WeightArr: #{binaryArr}"
# loops through the arr adding the elements together for the total(decimal value)
decimalInt = 0
binaryArr.each_index do |x|
thisVal = binaryArr[x].to_i
decimalInt += thisVal
if binaryArr[x+1]==nil then
break
end
end
puts "Decimal Value: #{decimalInt}"
当然,您可以删除这一行:if binaryArr[index]=0然后
end
请注意,如果n=157
,则其二进制表示形式为arr=n.to_s(2).chars#=>[“1”、“0”、“0”、“1”、“1”、“0”、“1”]
。因此,如果您从arr
开始,那么arr.join(“”).to_i(2)#=>157
。查看和的文档。