Python 平方根

Python 3 教程 · 2019-02-12 08:43:47

平方根,又叫二次方根,表示为〔√ ̄〕,如:数学语言为:√ ̄16=4。语言描述为:根号下16=4。

以下实例为通过用户输入一个数字,并计算这个数字的平方根:

实例(Python 3.0+)

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.codercto.com num = float(input('请输入一个数字: ')) num_sqrt = num ** 0.5 print(' %0.3f 的平方根为 %0.3f'%(num ,num_sqrt))

执行以上代码输出结果为:

$ python test.py 
请输入一个数字: 4
 4.000 的平方根为 2.000

在该实例中,我们通过用户输入一个数字,并使用指数运算符 ** 来计算该数的平方根。

该程序只适用于正数。负数和复数可以使用以下的方式:

实例(Python 3.0+)

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.codercto.com # 计算实数和复数平方根 # 导入复数数学模块 import cmath num = int(input("请输入一个数字: ")) num_sqrt = cmath.sqrt(num) print('{0} 的平方根为 {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

执行以上代码输出结果为:

$ python test.py 
请输入一个数字: -8
-8 的平方根为 0.000+2.828j

该实例中,我们使用了 cmath (complex math) 模块的 sqrt() 方法。

点击查看所有 Python 3 教程 文章: https://www.codercto.com/courses/l/10.html

查看所有标签

Algorithms

Algorithms

Robert Sedgewick、Kevin Wayne / Addison-Wesley Professional / 2011-3-19 / USD 89.99

Essential Information about Algorithms and Data Structures A Classic Reference The latest version of Sedgewick,s best-selling series, reflecting an indispensable body of knowledge developed over the ......一起来看看 《Algorithms》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具