定义函数:def square_root(x),求x的平方根,如果x是负数,则抛出ArithmeticError异常,否则调用数学函数sqrt返回x的平方根。 编写一个main函数,输入一个数,调用square_root函数,显示它的平方根或处理异常。
时间: 2023-03-11 10:08:45 浏览: 108
def main():
while True:
try:
x = int(input("输入一个数:"))
result = square_root(x)
print("{}的平方根是{}".format(x, result))
except ArithmeticError:
print("负数没有平方根")def square_root(x):
if x < 0:
raise ArithmeticError
else:
return math.sqrt(x)main()
相关问题
用一条语句输出x的平方根,如果是负数则绝对值
import math
x = float(input("请输入一个数: "))
if x >= 0:
print(math.sqrt(x))
else:
print(math.sqrt(abs(x)))
求一个非负数算术平方根的函数***为sqrt(x))。
以下是使用牛顿迭代法实现求一个非负数算术平方根的函数sqrt(x)的Python代码:
```python
def sqrt(x):
if x == 0:
return 0
else:
last = 0.0
current = 1.0
while last != current:
last = current
current = (current + x / current) / 2
return current
```
该函数使用了牛顿迭代法,通过不断逼近平方根的值,最终得到一个精确的结果。在函数中,我们首先判断输入的数是否为0,如果是,则直接返回0;否则,我们初始化两个变量last和current,分别表示上一次和当前的逼近值。然后,我们进入一个while循环,不断更新last和current的值,直到它们相等为止。在每次更新current的值时,我们使用牛顿迭代公式:current = (current + x / current) / 2。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)