如何求 Python 中负数的开方

How To Find The sqrt Of A Negative Number In Python

当我输入负数时,它会给出 NaN(不是数字)作为答案

import math
x = int(input("Enter a number"))
x = math.sqrt(x)
print(x)

负数的平方根是复数,因此您需要 cmath复杂 数学)模块:

>>> import cmath
>>> cmath.sqrt(-1)
1j
>>> cmath.sqrt(1 - 2j)
(1.272019649514069-0.7861513777574233j)