2014-07-19 27 views
-6

我的理解是,代碼是將毫秒轉換爲秒,分鐘和小時,但我不明白「%」的作用是什麼... int seconds =(int)(milliseconds/1000)%60;java中的數學 - 「%」做什麼?

有人可以解釋一下嗎?

我可以在C++中執行相同的操作嗎? 謝謝!!

   milliseconds = ((System.currentTimeMillis()) - (startTime)); 
      int seconds = (int) (milliseconds/1000) % 60 ; 
      int minutes = (int) ((milliseconds/(1000*60)) % 60); 
      int hours = (int) ((milliseconds/(1000*60*60)) % 24); 

回答

3

%是Modulus運算符。對於Java Modulus

"% Modulus - Divides left hand operand by right hand operand and returns remainder" 

例如:10%3等於1直觀地看到這一點 -

10 % 3 
10 - 3 = 7 // Start by subtracting the right hand side of the % operator 
7 - 3 = 4  // Continue subtraction on remainders 
4 - 3 = 1 
Now you can't subtract 3 from 4 without going negative so you stop. 
You have 1 leftover as a remainder so that is your answer. 

你可以把它看作是「我是多麼將不得不減去的值在左邊爲了使它能夠被右邊的值整除?「


是的,實際上這是C++模數的相同符號。


「在算術中,其餘部分是整數除以一個整數後產生整數商(整數除法)」。

「在計算中,模(有時稱爲模)操作發現一個數除以另一個的餘數。」

+0

我在一些網站上也讀過它......但我還是不明白 – Helena

+0

@ Helena你知道餘數是多少嗎? –

+1

@Helena:如果你用'5'分割一個整數(又名「整數」)如'17',結果是'3',但是剩下一個'2',因爲'17 = 5 * 3 + 2'。剩下的就是「休息」,這就是'%'返回的結果。換句話說:'17/5 - > 3','17%5 - > 2'。 –