python 中的平方根循环
Square root loop in 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
这是一种怪异的方法,或者至少没有多大意义,因为它使变量 sqrt_num 不是平方根,但我会将计数初始化为 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 = '')
我需要输入一个大于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
这是一种怪异的方法,或者至少没有多大意义,因为它使变量 sqrt_num 不是平方根,但我会将计数初始化为 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 = '')