在python中使用负数

2024-05-14 21:36:35 发布

您现在位置: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

我想没有绝对的,但每次我输入负数,我都会得到一个很大的脂肪。我知道有一个简单的方法,我就是找不到。


Tags: 程序概念input编程countabsvariables实验室
3条回答

也许你会用一些效果

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是否为负。如果它是numa乘以-1,然后做numb = abs(numb)。然后做循环。

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

相关问题 更多 >

    热门问题