Pergunta

Sou estudante em conceitos de aula de programação. O laboratório é administrado por um TA e hoje em laboratório, ele nos deu um pequeno programa simples para construir. Foi aquele em que se multiplicaria por adição. De qualquer forma, ele nos fez usar absoluto para evitar quebrar o prog com negativos. Eu ancinei bem rápido e depois discuti com ele por 10 minutos que era uma matemática ruim. Era 4 * -5 não é igual a 20, é igual a -20. Ele disse que realmente não se importa com isso e que seria muito difícil fazer com que o prog lide com os negativos de qualquer maneira. Então, minha pergunta é como faço para fazer isso.

Aqui está o prog que entreguei:

#get user input of numbers as variables

numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0
count = 0

#output the total
while (count< abs(numb)):
    total = total + numa
    count = count + 1

#testing statements
if (numa, numb <= 0):
    print abs(total)
else:
    print total

Eu quero fazer isso sem absolutos, mas toda vez que insiro números negativos, recebo um grande gaosegg. Eu sei que há uma maneira simples de fazer isso, simplesmente não consigo encontrá -lo.

Foi útil?

Solução

Talvez você conseguisse isso com algo no efeito de

text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.

if b > 0:
    num_times = b
else:
    num_times = -b

total = 0
# While loops with counters basically should not be used, so I replaced the loop 
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
    total += a 
    # We do this a times, giving us total == a * abs(b)

if b < 0:
    # If b is negative, adjust the total to reflect this.
    total = -total

print total

ou talvez

a * b

Outras dicas

Demasiado difícil? Seu TA é ... bem, a frase provavelmente me iria banir. De qualquer forma, verifique se numb é negativo. Se for, multiplique numa por -1 e fazer numb = abs(numb). Em seguida, faça o loop.

O ABS () é necessário enquanto a condição é necessária, pois, bem, controla o número de iterações (como você definiria um número negativo de iterações?). Você pode corrigi -lo invertendo o sinal do resultado se numb é negativo.

Portanto, esta é a versão modificada do seu código. Nota Eu substituí o loop while por um limpador para loop.

#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0

#output the total
for count in range(abs(numb)):
    total += numa

if numb < 0:
    total = -total

print total

Experimente isso no seu TA:

# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)

for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
    print numa, numb,
    accum = 0
    negate = False
    if numa < 0:
        negate = True
        numa = -numa
    while numa:
        if numa & 1:
            accum += numb
        numa >>= 1
        numb <<= 1
    if negate:
        accum = -accum
    print accum

resultado:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129

Que tal algo assim? (Não usa abs () nem mulitiplicação)
Notas:

  • A função ABS () é usada apenas para o truque de otimização. Este trecho pode ser removido ou recodificado.
  • A lógica é menos eficiente, pois estamos testando o sinal de A e B a cada iteração (preço a pagar para evitar o ABS () e o operador de multiplicação)

def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
   if abs(a) > abs(b):
      a, b = b, a     # optimize by reducing number of iterations
   total = 0
   while a != 0:
      if a > 0:
         a -= 1
         total += b
      else:
         a += 1
         total -= b
   return total

multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12

Obrigado a todos, todos vocês me ajudaram a aprender muito. Isso é o que eu criei usando algumas de suas sugestões

#this is apparently a better way of getting multiple inputs at the same time than the 
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])

#standing variables
total = 0

if numb > 0:
    repeat = numb
else:
    repeat = -numb

#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
    total += numa


#check to make sure the output is accurate
if numb < 0:
    total = -total


print total

Obrigado por toda a ajuda a todos.

import time

print ('Two Digit Multiplication Calculator')
print ('===================================')
print ()
print ('Give me two numbers.')

x = int ( input (':'))

y = int ( input (':'))

z = 0

print ()


while x > 0:
    print (':',z)
    x = x - 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',z)

while x < 0:
    print (':',-(z))
    x = x + 1
    z = y + z
    time.sleep (.2)
    if x == 0:
        print ('Final answer: ',-(z))

print ()  
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top