Как умножить путем повторного сложения с использованием Python - PullRequest
0 голосов
/ 02 июля 2019

Я не могу отобразить необходимый вывод для моей домашней работы. Где мне нужно изменить мой код?

Вопрос в следующем: Умножение путем повторного сложения Пример: 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]

1 Ответ

0 голосов
/ 02 июля 2019

Судя по количеству кода здесь, кажется, что этот вопрос более сложный, чем общая информация.Чтобы получить эффект умножения целых чисел пользовательского ввода, я бы сделал это:

x = int(input("Enter the multiplicand: "))
y = int(input("Enter the multiplier: "))

result = 0 #this will be the ultimate answer

if y < 0:   #figure out if y is negative
    count = -y #establish a counter
else:
    count = y

while count > 0: #set the condition for your loop. If count == 0, it will loop 0 times. result is already set to 0. 
    if x == 0: 
        count = 0      #this will exit the loop. Other options include "break"
    result += x        #this will only execute if x doesn't equal 0. 
    count -= 1         # when this value equals 0, loop ends, and the result is set.

print result
...