且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不使用乘法的情况下使用while进行乘法?

更新时间:2023-09-09 22:50:52

您可以重复使用加法.

def multiply(a,b):
    total = 0
    counter = 0
    while counter < b:
        total += a
        counter += 1
    return total

>>> multiply(5,3)
15

考虑一下,要将两个整数相乘,只需将一个整数相乘多次即可.例如:

Think about it, to multiply two integers, you just add one integer that many times. For example:

5 x 3 = 5 + 5 + 5 = 15