python加法与乘法编程题,如何使用python通过重复加法进行乘法?

我无法显示作业所需的输出。我需要在哪里更改代码?在

问题是:

重复加法乘法

例:5+5+5+5

我是工程系二年级学生,编程初学者。我缺乏编写代码的技能和背景。我已经做了好几天了,还是没有发现问题。我们的大学教授还没有教我们这一课,所以我对编程还是不熟悉。在#4bit by 4bit multiplication through repeated addition.

#Example: 5 x 6 = 5+5+5+5+5+5

def multiply(x,y):

#Any number multiplied by 0 will result to 0.

if(y == 0):

return 0

#This will repeatedly add ‘x’, ‘y’ times.

if(y > 0 ):

return (x + multiply(x, y - 1))

#When 'y' is negative...

if(y < 0 ):

return -multiply(x, -y)

def add(x, y):

max_len = max(len(x), len(y))

x = x.zfill(max_len)

y = y.zfill(max_len)

result = ""

carry = 0

for i in range(max_len - 1, -1, -1):

r = carry

r += 1 if x[i] == "1" else 0

r += 1 if y[i] == "1" else 0

result = ("1" if r % 2 == 1 else "0") + result

carry = 0 if r < 2 else 1

if carry != 0: result = "1" + result

return result.zfill(max_len)

#This will convert the binary number to an integer.

def conv(binary):

exponent = 0

total = 0

for digit in reversed(binary):

if digit == "1":

total += 2 ** exponent

exponent += 1

return total

#The user will input numbers here:

c = int(input("Enter the multiplicand: "))

d = int(input("Enter the multiplier: "))

result1=c

a=(bin(c)[2:])

b=(bin(d)[2:])

result=a

print("The binary value of the multiplicand is ",a)

print("The binary value of the multiplier is ",b)

for i in range(conv(b) - 1):

print("{} + {}".format(result, a), end="")

result = add(result, a)

print("= {}".format(result))

这是输出:

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值