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

更新於: 2023年10月19日

1K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告