2011-03-29 80 views
0

我有一个用户输入'n',我找到了平方根。我知道的是math.sqrt(n),但我需要让程序继续找到平方根,直到它小于2.同时返回给用户程序运行多少次以找到小于2的根,使用计数器。我正在使用python。使用Python的平方根循环有问题

到目前为止:

import math 
root = 0 
n = input('Enter a number greater than 2 for its root: ') 

square_root = math.sqrt(n) 
print 'The square root of', n, 'is', square_root 

keep_going = 'y' 

while keep_going == 'y': 
    while math.sqrt(n) > 2: 
     root = root + 1 
+3

如果这是家庭作业,请将其标记为此类。 – Oddthinking 2011-03-29 02:46:40

+0

你做了什么? – 2011-03-29 02:47:44

+0

你应该把你的代码放到原来的问题中。这将使其可读性更强,特别是在使用缩进的情况下。 – JoshAdel 2011-03-29 03:17:20

回答

1
import math 
user_in = input() 
num = int(user_in) 

num = math.sqrt(num) 
count = 1 
while(num > 2): 
    num = math.sqrt(num) 
    count += 1 

print count 
+1

Python 2的'raw_input'当然是:-) – paxdiablo 2011-03-29 02:52:53

+2

为什么你要解决人们这样的作业......在3年内,他将坐在你的隔间旁边...... – iluxa 2011-03-29 02:55:29

0

假设2.x的

count = 0 
user_input = int(raw_input("enter:")) 
while true:  
    num = math.sqrt(user_input) 
    if num < 2: break 
    print num 
    count+=1 
print count  

错误检查用户输入不存在。

0

明显的方式:

def sqrtloop(n): 
    x = 0 
    while n >= 2: 
     n **= 0.5 
     x += 1 
    return x 

没有那么多:

def sqrtloop2(n): 
    if n < 2: 
     return 0 
    return math.floor(math.log(math.log(n, 2), 2)) + 1 
+0

请注意[Python Style Guide] (http://www.python.org/dev/peps/pep-0008/)说你应该在增大的赋值(** =,+ =),比较(<)和赋值(=)之间使用空格函数参数列表定义默认值时)。另外,你应该_re rt _ _不_在一行上写复合语句,比如'if n <2:return 0'。 – 2011-03-29 08:06:40

+0

@lazyr:都是真的。固定。 – Kabie 2011-03-29 09:23:37