Ruby on rails RubyonRails函数定义的失败测试

Ruby on rails RubyonRails函数定义的失败测试,ruby-on-rails,Ruby On Rails,我已经定义了一个函数,该函数接受一个数字,如果它是一个 2的幂。否则,返回false: def is_power_of_two?(num) n = 0 res = false if num % 2 == 0 while 2^n <= num if 2^n == num res = true end n += 1 end end puts(n.to_s) return res end # Thes

我已经定义了一个函数,该函数接受一个数字,如果它是一个 2的幂。否则,返回false:

def is_power_of_two?(num)
  n = 0
  res = false
  if num % 2 == 0
    while 2^n <= num
      if 2^n == num
        res = true
      end
      n += 1
    end 
  end
  puts(n.to_s)
  return res
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts('is_power_of_two?(1) == true: ' + (is_power_of_two?(1) == true).to_s)
puts('is_power_of_two?(16) == true: ' + (is_power_of_two?(16) == true).to_s)
puts('is_power_of_two?(64) == true: ' + (is_power_of_two?(64) == true).to_s)
puts('is_power_of_two?(78) == false: ' + (is_power_of_two?(78) == false).to_s)
puts('is_power_of_two?(0) == false: ' + (is_power_of_two?(0) == false).to_s)

打印出来的结果似乎与预期相符,但测试仍然失败。有人知道为什么会这样吗

您总是想检查它是否是2的幂,这样当它不是2的幂时,它会返回false


这感觉像是一个家庭作业问题,所以我不会给你确切的答案,但这应该会让你朝着正确的方向前进。

如果你期望计算功率,那么这是错误的^XOR计算功率使用**

2^2 # 0
2**2 # 4

正如mohamed ibrahm所说,您使用了错误的运算符

插入符号是按位异或运算。因此
2^3==1
(因为十进制2在二进制中是010,十进制3在二进制中是011,并且除最后一位外,所有位都相同,所以结果是001或十进制1)

幂运算是由双星号完成的,因此
2**3==8

下面是对各种操作符的描述

2^2 # 0
2**2 # 4