为什么此代码找不到权力? (红宝石) [英] Why Can't This Code Find Powers? (Ruby)
问题描述
App Academy的实践测试表明,他们选择的查找输入是否为2的幂的方法是在循环上继续将其除以2,并检查最终结果是1还是0(在测试了数字1和2之后, 0作为输入),这很有意义,但是为什么这种方式不起作用?
App Academy's practice test says their chosen way of finding if an input is a power of 2 is to keep dividing it by 2 on a loop and check whether the end result is 1 or 0 (after having tested for the numbers 1 and 0 as inputs), which makes sense, but why won't this way work?
def try
gets(num)
counter = 0
go = 2 ** counter
if num % go == 0
return true
else
counter = counter + 1
end
return false
end
除非计数器不起作用,否则我无法弄清楚为什么它不起作用.
I can't figure out why this won't work, unless the counter isn't working.
推荐答案
您的代码存在许多问题.
There are a number of problems with your code.
-
首先,没有循环,并且由于
counter = 0
,如果您打算在循环中使用该方法,则每次计数器都会重置为零.
First of all, there is no loop and your counter will reset to zero each time if you intend to use the method in a loop, because of
counter = 0
.
counter = 0; go = 2 ** counter
基本上表示go = 2 ** 0
,即1
.因此,num % 1
将始终为0
counter = 0; go = 2 ** counter
basically means go = 2 ** 0
which is 1
. Therefore num % 1
will always be 0
实际上,您需要对数字进行除法并在此过程中进行更改. 12 % 4
将返回0
,但您不知道12是否为2的幂.
You actually need to divide the number and change it in the process. 12 % 4
will return 0
but you don't know by that if 12 is a power of 2.
IO#gets 返回一个字符串,并使用分隔符作为参数,因此您需要使用num = gets.to_i
来实际获取变量num中的数字.您要将num
赋予gets
作为参数,但这并不能满足您的要求.
IO#gets returns a string and takes a separator as an argument, so you need to use num = gets.to_i
to actually get a number in the variable num. You are giving num
to gets
as an argument, this does not do what you want.
尝试:
# 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
这篇关于为什么此代码找不到权力? (红宝石)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!