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://codercto.com/courses/l/10.html

查看所有标签

Learning Python, 5th Edition

Learning Python, 5th Edition

Mark Lutz / O'Reilly Media / 2013-7-6 / USD 64.99

If you want to write efficient, high-quality code that's easily integrated with other languages and tools, this hands-on book will help you be productive with Python quickly. Learning Python, Fifth Ed......一起来看看 《Learning Python, 5th Edition》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具