Home  >  Article  >  Backend Development  >  Why in Python, -22 // 10 returns -3?

Why in Python, -22 // 10 returns -3?

WBOY
WBOYforward
2023-09-13 13:13:02911browse

为什么在Python中,-22 // 10 返回 -3?

In Python, -22//10 returns -3 because of the concept of base division, the double slash operator. // is a double slash, the arithmetic operator. Let’s understand it first.

Floor division in Python

Division of operands, the result is the quotient obtained by removing the digits after the decimal point. But if one of the operands is negative, the result will be rounded, i.e. rounded starting from zero (rounding towards negative infinity).

In Python, // is the double slash operator, which is floor division. //Operator used to perform division that rounds the result down to the nearest integer. //The use of operators is very simple. We will also compare with the result of single slash division. Let’s look at the syntax first −

a and b are the first st and the second nd digit:

a // b

Example of // (double slash) operator

Let us now look at an example of implementing the double slash operator in Python -

a = 37
b = 11

# 1st Number
print("The 1st Number = ",a)

# 2nd Number
print("The end Number = ",b)

# Dividing using floor division
res = a // b
print("Result of floor division = ", res)

Output

('The 1st Number = ', 37)
('The end Number = ', 11)
('Result of floor division = ', 3)

Use negative numbers to implement the // (double slash) operator

The Chinese translation of

Example

is:

Example

We will try using the double slash operator and negative numbers as input. Let’s look at an example

# A negative number with a positive number
a = -37
b = 11

# 1st Number
print("The 1st Number = ",a)

# 2nd Number
print("The end Number = ",b)

# Dividing using floor division
res = a // b
print("Result of floor division = ", res)

Output

('The 1st Number = ', -37)
('The end Number = ', 11)
('Result of floor division = ', -4)
The Chinese translation of

Example

is:

Example

As you can see in the output above, using negative numbers does not affect rounding. The result is rounded down. Now, we can use the double slash operator to check -22 // 10 -

# A negative number with a positive number
a = -22
b = 10

# 1st Number
print("The 1st Number = ",a)

# 2nd Number
print("The end Number = ",b)

# Dividing using floor division
res = a // b
print("Result of floor division = ", res)

Output

('The 1st Number = ', -22)
('The end Number = ', 10)
('Result of floor division = ', -3)

The above is the detailed content of Why in Python, -22 // 10 returns -3?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete