为什么本代码无法找到权力? (ruby)

App Academy的练习测试表明,他们选择的方法是查找输入是否为2的幂是在循环中将其除以2并检查最终结果是1还是0(在测试数字1和0作为输入之后) ),这是有道理的,但为什么这种方式不起作用?

def try gets(num) counter = 0 go = 2 ** counter if num % go == 0 return true else counter = counter + 1 end return false end 

我无法弄清楚为什么这不起作用,除非计数器不起作用。

您的代码存在许多问题。

  1. 首先,没有循环,如果你打算在循环中使用该方法,你的计数器将重置为零,因为counter = 0

  2. counter = 0; go = 2 ** counter counter = 0; go = 2 ** counter基本上意味着go = 2 ** 01 。 因此num % 1将始终为0

  3. 您实际上需要划分数字并在此过程中更改它。 12 % 4将返回0但你不知道12如果12是2的幂。

  4. IO#gets返回一个字符串并将一个分隔符作为参数,因此您需要使用num = gets.to_i来实际获取变量num中的数字。 你给num作为一个参数,这不会做你想要的。

尝试:

 # Check if num is a power of 2 # # @param num [Integer] number to check # @return [Boolean] true if power of 2, false otherwise def power_of_2(num) while num > 1 # runs as long as num is larger than 1 return false if (num % 2) == 1 # if number is odd it's not a power of 2 num /= 2 # divides num by 2 on each run end true # if num reached 1 without returning false, it's a power of 2 end 

我为你的代码添加了一些检查。 注意, gets(num)返回一个String。 你的代码很好,但不适用于Ruby。 Ruby讨厌像Perl那样的类型交叉转换。

 def try(num = 0) # here we assure that num is number unless (num.is_a?(Integer)) puts "oh!" return false end counter = 0 go = 2 ** counter if num % go == 0 return true else counter = counter + 1 end return false end 

一般问题是“字符串如何使用’%’运算符与数字?”

尝试解释器中的一些代码( irb ):

 "5" % 2 

要么

 "5" % 0