15

我是编程课程概念的学生。该实验室由一名 TA 管理,今天在实验室他给了我们一个非常简单的小程序来构建。这是一个可以通过加法相乘的方法。无论如何,他让我们使用 absolute 来避免用底片破坏前卫。我很快就把它搅了起来,然后和他争论了 10 分钟,说这是一个糟糕的数学。原来,4 * -5 不等于 20,它等于 -20。他说他真的不在乎这个,无论如何让前卫处理负面因素太难了。所以我的问题是我该怎么做。

这是我上交的编:

#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

我想在没有绝对的情况下做到这一点,但每次我输入负数时,我都会得到一个大胖子。我知道有一些简单的方法可以做到这一点,我就是找不到。

4

8 回答 8

7

也许你会用一些大意的东西来完成这个

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
于 2010-03-16T02:52:30.897 回答
4

太难?你的助教是……嗯,这句话可能会让我被禁止。无论如何,请检查是否numb为负数。如果是则乘以numa-1numb = abs(numb)。然后做循环。

于 2010-03-16T02:50:30.387 回答
3

while 条件中的 abs() 是必需的,因为它控制迭代次数(如何定义负迭代次数?)。如果numb为负,您可以通过反转结果的符号来纠正它。

所以这是您的代码的修改版本。注意我用更干净的 for 循环替换了 while 循环。

#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
于 2010-03-16T03:03:16.617 回答
1

在你的助教上试试这个:

# 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

输出:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
于 2010-03-16T04:13:00.487 回答
0

那样的事情怎么样?(不使用 abs() 或乘法)
注意:

  • abs() 函数仅用于优化技巧。可以删除或重新编码此代码段。
  • 逻辑效率较低,因为我们每次迭代都在测试 a 和 b 的符号(避免 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
于 2010-03-16T03:13:52.677 回答
0

谢谢大家,你们让我学到了很多东西。这就是我使用您的一些建议得出的结论

#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

谢谢各位的帮助。

于 2010-03-16T23:42:41.590 回答
0

尝试这样做:

num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
ans = num1*num2


if num1 > 0 or num2 > 0:
    print(ans)

elif num1 > 0 and num2 < 0 or num1 < 0 and num1 > 0:
    print("-"+ans)

elif num1 < 0 and num2 < 0:
    print("Your product is "+ans)
else:
    print("Invalid entry")
于 2021-12-02T02:46:13.930 回答
-1
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 ()  
于 2014-11-10T20:34:49.070 回答