Я не могу отобразить необходимый вывод для моей домашней работы. Где мне нужно изменить мой код?
Вопрос в следующем:
Умножение путем повторного сложения
Пример: 5 x 6 = 5 + 5 + 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))
Это вывод:
Enter the multiplicand: 5
Enter the multiplier: 6
The binary value of the multiplicand is 101
The binary value of the multiplier is 110
101 + 101= 1010
1010 + 101= 1111
1111 + 101= 10100
10100 + 101= 11001
11001 + 101= 11110
The product of 5 and 6 is 30
The product in binary is: 101 x 110 = 11110
5 + 5Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module> start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start exec(open(mainpyfile).read(), _main_.__dict__)
File "<string>", line 68, in <module>
File "<string>", line 20, in add
TypeError: object of type 'int' has no len()
[Program finished]