gpt4 book ai didi

python - 在 python 中使用负数

转载 作者:太空狗 更新时间:2023-10-29 18:04:13 26 4
gpt4 key购买 nike

我是编程概念类(class)的学生。该实验室由助教管理,今天在实验室他给了我们一个真正简单的小程序来构建。这是一个乘以加法的地方。无论如何,他让我们使用 absolute 以避免用底片破坏 prog。我很快就把它搞定了,然后和他争论了 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

我想不用绝对值,但每次我输入负数时,我都会得到一个大胖鹅蛋。我知道有一些简单的方法可以做到,我就是找不到。

最佳答案

也许你会用一些效果来完成这个

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

关于python - 在 python 中使用负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2451776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com