python中的平方根循环

欧洲14

我需要输入大于2的数字,并取平方根,直到平方根小于2。我需要一个打印语句,其中包括该数字的平方根被获取的次数以及输出。到目前为止,我有:

import math

input_num = float(input("Enter a number greater than two: "))

while input_num < 2:
    input_num = float(input("Enter a number greater than two: "))
else:
    sqrt_num = math.sqrt(input_num)
    count = 1
    while sqrt_num > 2:
        sqrt_num = math.sqrt(sqrt_num)
        count += 1
        print(count, ": ", sqrt_num, sep = '')

输出为:

Enter a number greater than two: 20
2: 2.114742526881128
3: 1.4542154334489537

我想包括count 1的第一次迭代。如何编写适当的循环,使其看起来像

Enter a number greater than two: 20
1: 4.47213595499958
2: 2.114742526881128
3: 1.4542154334489537
Dyspro

这种方式很简单,或者至少没有太大意义,因为它使变量sqrt_num不是平方根,但是我将count初始化为0并将sqrt_num初始化为input_num,如下所示:

import math

input_num = float(input("Enter a number greater than two: "))

while input_num < 2:
    input_num = float(input("Enter a number greater than two: "))
else:
    sqrt_num = input_num
    count = 0
    while sqrt_num > 2:
        sqrt_num = math.sqrt(sqrt_num)
        count += 1
        print(count, ": ", sqrt_num, sep = '')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章