在 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
我想在没有绝对的情况下做到这一点,但是每次我输入负数时,我都会得到一个大胖鹅蛋。我知道有一些简单的方法可以做到这一点,但我找不到。
I am a student in a concepts of programming class. The lab is run by a TA and today in lab he gave us a real simple little program to build. It was one where it would multiply by addition. Anyway, he had us use absolute to avoid breaking the prog with negatives. I whipped it up real quick and then argued with him for 10 minutes that it was bad math. It was, 4 * -5 does not equal 20, it equals -20. He said that he really dosen't care about that and that it would be too hard to make the prog handle the negatives anyway. So my question is how do I go about this.
here is the prog I turned in:
#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
I want to do it without absolutes, but every time I input negative numbers I get a big fat goosegg. I know there is some simple way to do it, I just can't find it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
效果的东西来实现这一点
也许你会通过一些达到或可能
Perhaps you would accomplish this with something to the effect of
or maybe
太难了?你的助教是……好吧,这个短语可能会让我被禁止。无论如何,检查一下
numb
是否为负数。如果是,则将numa
乘以-1
并执行numb = abs(numb)
。然后做循环。Too hard? Your TA is... well, the phrase would probably get me banned. Anyways, check to see if
numb
is negative. If it is then multiplynuma
by-1
and donumb = abs(numb)
. Then do the loop.while 条件中的 abs() 是必需的,因为它控制迭代次数(如何定义负迭代次数?)。如果
numb
为负数,您可以通过反转结果的符号来纠正它。这是您的代码的修改版本。注意我用更干净的 for 循环替换了 while 循环。
The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if
numb
is negative.So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.
在你的 TA 上试试这个:
输出:
Try this on your TA:
output:
类似的事情怎么样? (不使用 abs() 也不使用乘法)
注意:
How about something like that? (Uses no abs() nor mulitiplication)
Notes:
谢谢大家,你们帮助我学到了很多。这是我根据大家的建议得出的结论,
感谢大家的帮助。
Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions
Thanks for all the help everyone.
尝试这样做:
Try doing this: