python中的平方根循环

我需要输入一个大于 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

我想包括计数 1 的第一次迭代。如何编写一个正确的循环,使其看起来像:


Enter a number greater than two: 20

1: 4.47213595499958

2: 2.114742526881128

3: 1.4542154334489537


摇曳的蔷薇
浏览 407回答 1
1回答

尚方宝剑之说

这是一种很老套的方法,或者至少没有多大意义,因为它使变量 sqrt_num 不是平方根,但我会将 count 初始化为 0 并将 sqrt_num 初始化为 input_num,如下所示:import mathinput_num = float(input("Enter a number greater than two: "))while input_num < 2:&nbsp; &nbsp; input_num = float(input("Enter a number greater than two: "))else:&nbsp; &nbsp; sqrt_num = input_num&nbsp; &nbsp; count = 0&nbsp; &nbsp; while sqrt_num > 2:&nbsp; &nbsp; &nbsp; &nbsp; sqrt_num = math.sqrt(sqrt_num)&nbsp; &nbsp; &nbsp; &nbsp; count += 1&nbsp; &nbsp; &nbsp; &nbsp; print(count, ": ", sqrt_num, sep = '')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python