如何用Python解决x 的平方根问题
1、#输入: 8
#输出: 2
#说明: 8 的平方根是 2.82842...,
#由于返回类型是整数,小数部分将被舍去。
2、4 ** 2
#我们要知道4的2次方可以这么写。
3、4 ** 0.5
#那么相反,4的平方根就是这么写。得到的结果是浮点型。
4、def mySqrt(x):
result_f = x ** 0.5
#那么我们首先把整数直接运算,算出平方根。
5、def mySqrt(x):
result_f = x ** 0.5
result_s = str(result_f)
#然后我们要把浮点型转换为字符串。
6、def mySqrt(x):
result_f = x ** 0.5
result_s = str(result_f)
dot = result_s.index(".")
#这个时候我们要找到小数点所处的位置。
7、def mySqrt(x):
result_f = x ** 0.5
result_s = str(result_f)
dot = result_s.index(".")
result_dot = result_s[:dot]
#这个时候我们只保留小数点前面的数字。
8、def mySqrt(x):
result_f = x ** 0.5
result_s = str(result_f)
dot = result_s.index(".")
result_dot = result_s[:dot]
result = int(result_s)
#最后要把字符串转换为整型。
9、def mySqrt(x):
result = str(x ** 0.5)
dot = result.index(".")
return int(result[:dot])
mySqrt(8)
#这个是简化的写法。