Я - студент в понятие программирования класса. Лаборатория выполняется TA, и сегодня в лаборатории он дал нам реальную простую небольшую программу для создания. Это было то, где это умножится дополнением. Так или иначе он сделал, чтобы мы использовали абсолютный, чтобы не повреждать прогр с отрицательными сторонами. Я сделал его на скорую руку реальный быстрый и затем обсужденный с ним в течение 10 минут, что это была плохая математика. Это было, 4 *-5 не равняется 20, это равняется-20. Он сказал, что действительно dosen't заботится об этом и что будет слишком трудно заставить прогр обработать отрицательные стороны так или иначе. Таким образом, мой вопрос состоит в том, как я иду об этом.
вот прогр, которую я возвратил:
#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
Я хочу сделать это без абсолютных понятий, но каждый раз я ввел отрицательные числа, я получаю большой goosegg. Я знаю, что существует некоторый простой способ сделать это, я просто не могу найти его.
Возможно, вы добьетесь этого с помощью чего-то вроде
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
или, может быть,
a * b
Слишком сложно? Ваш ТА ... ну, эта фраза, вероятно, меня забанит. В любом случае, проверьте, является ли numb
отрицательным. Если это так, умножьте число
на -1
и выполните numb = abs (numb)
. Затем сделайте петлю.
Попробуйте это на своем 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
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
Функция abs () в условии while необходима, поскольку она контролирует количество итераций (как бы вы определили отрицательное количество итераций?). Вы можете исправить это, изменив знак результата, если numb
отрицательное.
Итак, это измененная версия вашего кода. Обратите внимание, что я заменил цикл while на очиститель цикла for.
#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
Как насчет чего-то подобного? (Не использует ни abs(), ни мультипликацию)
.
Примечания:
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
Спасибо всем, вы все помогли мне многому научиться. Вот что я придумал, используя некоторые из ваших предложений
#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
Спасибо всем за помощь.