python 用加法实现a,b两数相乘

"""
思路:1.a * b = a + a + a + ...
   2.a * b = n个a相加,只需求证b = n即可
   3.用for 循环遍历即可,b就是range的最大次数
   4.需考虑a,b有五种情况存在,但结果会有三种,正数,0,负数
"""

def multiplication(a,b):
if a > 0 and b > 0:
sum = 0
for i in range(b):
sum += a
print(sum)
elif a < 0 and b < 0:
sum = 0
for i in range(-b):
sum += a
sum = -sum
print(sum)
elif a > 0 and b < 0:
sum = 0
for i in range(-b):
sum += a
print(-sum)
elif a < 0 and b > 0:
sum = 0
for i in range(b):
sum += a
print(sum)
else:
sum = 0
print(sum)
multiplication(8,5) #输出结果40
multiplication(-8,-5) #输出结果40
multiplication(8,-5) #输出结果-40
multiplication(-8,5) #输出结果-40
multiplication(0,-5) #输出结果0
multiplication(8,0) #输出结果0
posted @ 2019-09-04 11:02  范李2008  阅读(1416)  评论(0编辑  收藏  举报