2013-10-28 45 views
-7

如何在Python中存储一个负值为零的值?如何存储负值为零的值?

例子:

Enter a number:3 
Enter a number:4 
3 - 4 = 0 

答案居然是-1,而是因为答案是否定的,答案是存储为零。

请帮忙!

+0

“存储”或“你希望它是存储的”零?我假设后者,但必须多次阅读你的问题。 –

+2

我希望它被存储。大声笑! ;) –

回答

5

只需使用一个条件表达式:

result = 3 - 4 
total = 0 if result < 0 else result 
6

您可以使用内置max

a = 3 
b = 4 
total = max(0, a-b) # total == 0 
total = max(0, b-a) # total == 1 
+0

+1。但OP希望_answer_ ['被存储'](http://stackoverflow.com/questions/19632085/how-do-i-store-a-value-that-is-negative-as-zero#comment29146700_19632085) :) – devnull

+0

谢谢。我会更新答案。 –

+0

我需要使用if语句。 –