📜  Python程序查找两个数字的商和余数

📅  最后修改于: 2022-05-13 01:55:28.335000             🧑  作者: Mango

Python程序查找两个数字的商和余数

给定两个数 n 和 m。任务是通过将 n 除以 m 来找到两个数的商和余数。

例子:

Input:
n = 10
m = 3
Output:
Quotient:  3
Remainder 1

Input
n = 99
m = 5
Output:
Quotient:  19
Remainder 4

方法一:天真的方法

天真的方法是使用双除(//)运算符求商,使用模数(%)运算符求余数。

例子:

Python3
# Python program to find the
# quotient and remainder
  
def find(n, m):
      
    # for quotient
    q = n//m
    print("Quotient: ", q)
      
    # for remainder
    r = n%m
    print("Remainder", r)
      
# Driver Code
find(10, 3)
find(99, 5)


Python3
# Python program to find the
# quotient and remainder using
# divmod() method
  
  
q, r = divmod(10, 3)
print("Quotient: ", q)
print("Remainder: ", r)
  
q, r = divmod(99, 5)
print("Quotient: ", q)
print("Remainder: ", r)


输出:

Quotient:  3
Remainder 1
Quotient:  19
Remainder 4

方法二:使用 divmod() 方法

Divmod() 方法接受两个数字作为参数并返回包含商和余数的元组。

例子:

Python3

# Python program to find the
# quotient and remainder using
# divmod() method
  
  
q, r = divmod(10, 3)
print("Quotient: ", q)
print("Remainder: ", r)
  
q, r = divmod(99, 5)
print("Quotient: ", q)
print("Remainder: ", r)

输出:

Quotient:  3
Remainder 1
Quotient:  19
Remainder 4