Given a number, and we have to calculate its square in Python.

给定一个数字,我们必须在Python中计算其平方。

Example:

例:

    Input:
    Enter an integer numbers: 8

    Output:
    Square of 8 is 64

Calculating square is a basic operation in mathematics; here we are calculating the square of a given number by using 3 methods.

计算平方是数学中的基本运算。 在这里,我们使用3种方法计算给定数字的平方。

  1. By multiplying numbers two times: (number*number)

    将数字乘以两倍:( 数字*数字)

  2. By using Exponent Operator (**): (number**2)

    通过使用指数运算符( ** ):( 数字** 2)

  3. By using math.pow() method: (math.pow(number,2)

    通过使用math.pow()方法: (math.pow(number,2)

1)将数字相乘两次:(数字*数字) (1) By multiplying numbers two times: (number*number))

To find the square of a number - simple multiple the number two times.

查找数字的平方-将数字简单乘以两次。

Program:

程序:

# Python program to calculate square of a number
# Method 1 (using  number*number)

# input a number 
number = int (raw_input ("Enter an integer number: "))

# calculate square
square = number*number

# print
print "Square of {0} is {1} ".format (number, square)

Output

输出量

    Enter an integer number: 8
    Square of 8 is 64 

2)通过使用指数运算符(**):(数字** 2) (2) By using Exponent Operator (**): (number**2))

The another way is to find the square of a given number is to use Exponent Operator (**), it returns the exponential power. This operator is represented by **

另一种查找给定数字平方的方法是使用指数运算符 ( ** ),它返回指数幂。 该运算符由**表示

Example: Statement m**n will be calculated as "m to the power of n".

示例:语句m ** n将计算为 m乘以n 的幂”

Program:

程序:

# Python program to calculate square of a number
# Method 2 (using  number**2)

# input a number 
number = int (raw_input ("Enter an integer number: "))

# calculate square
square = number**2

# print
print "Square of {0} is {1} ".format (number, square)

Output

输出量

    Enter an integer number: 8
    Square of 8 is 64 


3)通过使用math.pow()方法:(math.pow(number,2) (3) By using math.pow() method: (math.pow(number,2))

pow(m,n) is an inbuilt method of math library, it returns the value of "m to the power n". To use this method, we need to import math library in the program.

pow(m,n)是数学库的一种内置方法,它将“ m的值返回给幂n” 。 要使用此方法,我们需要在程序中导入数学库。

The statement to import math library is import math.

导入数学库的语句是import math 。

Program:

程序:

# Python program to calculate square of a number
# Method 3 (using math.pow () method)

# importing math library 
import math 

# input a number 
number = int (raw_input ("Enter an integer number: "))

# calculate square
square = int(math.pow (number, 2))

# print
print "Square of {0} is {1} ".format (number, square)

Output

输出量

    Enter an integer number: 8
    Square of 8 is 64 

Recommended posts

推荐的帖子

翻译自: https://www.includehelp.com/python/calculate-square-of-a-given-number.aspx

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐