在Python中处理负数
我是一名编程概念课程的学生。今天在实验课上,助教给我们布置了一个很简单的小程序,让我们来做。这个程序是通过加法来实现乘法的。总之,他让我们使用绝对值来避免负数导致程序出错。我很快就写好了,然后和他争论了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
我想不使用绝对值,但每次输入负数时,程序就会出错。我知道有简单的方法可以做到这一点,只是我找不到。
8 个回答
3
在while条件中使用abs()是必要的,因为它控制了循环的次数(你怎么定义一个负的循环次数呢?)。如果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
4
觉得太难了吗?你的助教...嗯,这个说法可能会让我被禁言。不过,先检查一下 numb
是否是负数。如果是负数,就把 numa
乘以 -1
,然后把 numb
变成它的绝对值,也就是用 numb = abs(numb)
。接下来就可以开始循环了。
8
也许你可以用类似下面的方式来实现这个功能:
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