概述
我无法显示作业所需的输出。我需要在哪里更改代码?在
问题是:
重复加法乘法
例: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}$
最后
以上就是开心砖头为你收集整理的python加法与乘法编程题,如何使用python通过重复加法进行乘法?的全部内容,希望文章能够帮你解决python加法与乘法编程题,如何使用python通过重复加法进行乘法?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复