"如何只使用+=操作符实现加减乘除运算"(Python)

分析与解答:

1.加法操作:实现a+b的基本思路为对a执行b次+=操作即可

2.减法操作:实现a-b(a>=b)的基本思路为:不断对b执行+=操作,直到等于a,在这个过程中记录执行+=操作的次数;

3.乘法操作:实现a*b的基本思路为:利用已经实现的加法操作把a相加b次,就得到了a*b的值

4.除法操作:实现a/b的基本思路为:利用乘法操作,使b不断乘以1,2,....n,直到b*n>b时,就可以得到商为n-1

def add(a, b):
    """a+b"""
    if a < 0 and b < 0:
        print("无法用+=操作实现")
        return -1

    if b >= 0:
        i = 0
        while i < b:
            a += 1
            i += 1
        return a
    else:
        i = 0
        while i < a:
            b += 1
            i += 1
        return b

def minuus(a, b):
    """a-b"""
    if a < b:
        print("无法用+=操作实现")
        return -1
    result = 0
    while b != a:
        b += 1
        result += 1
    return result

def multi(a, b):
    """a*b"""
    if a <= 0 or b <= 0:
        print("无法用+=操作实现")
        return -1

    result = 0
    i = 0
    while i < b:
        result = add(result, a)
        i += 1
    return result

def divide(a, b):
    if a <= 0 or b <= 0:
        print("无法用+=操作实现")
        return -1
    result = 1
    tmpMulti = 0

    while True:
        tmpMulti = multi(b, result)
        if tmpMulti <= a:
            result += 1
        else:
            break
    return result - 1

if __name__ == "__main__":
    print(add(2, -4))
    print(minuus(2, -4))
    print(multi(2, 4))
    print(divide(9, 4))

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值