Ruby:为什么数组中的最后一个元素被改为1?

时间:2015-12-04 20:11:52

标签: 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_i将值保存到valueInt时,会发生这种情况。但是,同时有一个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

2 个答案:

答案 0 :(得分:2)

您正在为循环binaryArr ... binaryArr.reverse.each_index do内的end编制索引以获取值valueInt,但您应该为reverse编制索引。您可以在循环之前在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 then ... end

答案 1 :(得分:0)

  • if binaryArr[index]!=0 then根据输出binaryArr 包含字符串。 “a_string”!= 0将是真的。
  • 0**0的结果为1。