dma*_*000 11 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
Run Code Online (Sandbox Code Playgroud)
我想做的没有绝对,但每次我输入负数我得到一个大胖子鹅.我知道有一些简单的方法可以做到,我找不到它.
也许你会用这样的东西来完成这个
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
Run Code Online (Sandbox Code Playgroud)
或者可能
a * b
Run Code Online (Sandbox Code Playgroud)