在Python中遇到平方根循环问题

0 投票
4 回答
4588 浏览
提问于 2025-04-16 14:37

我有一个用户输入的数字'n',我想计算它的平方根。我知道可以用math.sqrt(n)来计算平方根,但我需要让程序一直计算平方根,直到结果小于2。同时,我还想告诉用户程序运行了多少次才能找到小于2的平方根,这需要用一个计数器来记录。我正在使用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

4 个回答

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
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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答