在python中使用负数

时间:2010-03-16 02:37:52

标签: python negative-number

我是编程课程概念的学生。该实验室由TA运营,今天在实验室中他给了我们一个简单的小程序来构建。它是一个可以通过添加繁殖的地方。无论如何,他让我们使用绝对来避免用底片打破前卫。我快速地将它掀起,然后和他争论了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

我想在没有绝对的情况下这样做,但每当我输入负数时,我会得到一个很大的肥胖鹅。我知道有一些简单的方法可以做到,我找不到它。

7 个答案:

答案 0 :(得分:5)

也许你会用

的效果实现这一目标
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

答案 1 :(得分:4)

太难了?你的TA是......好吧,这句话可能会让我被禁止。无论如何,检查numb是否为负数。如果是,则将numa乘以-1并执行numb = abs(numb)。然后做循环。

答案 2 :(得分:3)

需要while条件下的abs(),因为它控制着迭代次数(你将如何定义负的迭代次数?)。如果numb为负数,您可以通过反转结果的符号来更正它。

所以这是代码的修改版本。注意我用while循环替换了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

答案 3 :(得分:1)

在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

输出:

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

答案 4 :(得分:0)

这样的事情怎么样? (不使用abs()或mulitiplication)
注意:

  • 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

答案 5 :(得分: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

感谢所有人的帮助。

答案 6 :(得分:-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 ()