2013-10-28 46 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語句。 –