Python程序计算给定数字的平方
平方定义为数字自身相乘。数字n的平方表示为n2。从数学上讲,我们可以如下实现数字的平方。
$\mathrm{n^{2}=n*n}$
同样,我们也可以使用Python语言计算给定数字的平方。Python中有一些方法可以找到数字的平方,让我们一一来看。
使用指数运算符(**)
指数运算符用于执行指数算术运算。它用符号**表示。
语法
以下是使用指数运算符查找数字平方的语法。
$\mathrm{n^{2}=n**2}$
示例
在这个例子中,我们将使用指数运算符(**)计算25的平方。
n = 25
def exponential_operator(n):
sqaure_n = n ** 2
print("The square of",n,"is",sqaure_n)
exponential_operator(n)
输出
The square of 25 is 625
使用乘法运算符(*)
数字的平方可以通过将数字本身乘以自身来计算。这里,我们使用*运算符执行乘法。以下是语法。
$\mathrm{n^{2}=n*n}$
示例
这里,我们尝试使用乘法运算符(*)查找87的平方。
n = 87
def multiplication_operator(n):
square_n = n * n
print("The square of",n,"calculated using multiplication operator is",square_n)
multiplication_operator(n)
输出
The square of 87 calculated using multiplication operator is 7569
使用Math模块
Math模块是Python中可用的内置模块,用于执行数学任务。Math模块中提供了不同的函数,例如pow()、log()、cos()等。
pow()函数接受两个输入参数,一个是数字,另一个是要计算的数字的幂,然后返回幂输出。
语法
以下是math.pow()函数的语法。
import math n2 = pow(number,power)
示例
在这个例子中,我们将通过将14和2作为math模块的pow()函数的输入参数来计算14的平方,然后它返回14的平方。
import math
n = 14
p = 2
def power(n,p):
square_n = math.pow(n,p)
print("The square of",n,"calculated using multiplication operator is",square_n)
power(n,p)
输出
The square of 14 calculated using multiplication operator is 196.0
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP