[英]Why does the following code require the (int)?
Java方法Math.round
可以用於舍入數字。 以下哪個代碼片段將浮點數轉換為最接近的整數?
正確的答案是:
double f = 4.65
int n = (int) Math.round(f);
為什么不是以下原因:
double f = 4.65;
int n = Math.round(f);
Math.round(double)
返回long
,因此縮小范圍。
數學有兩種舍入方法。
static long round(double a)
//Returns the closest long to the argument.
static int round(float a)
//Returns the closest int to the argument.
您正在使用第一個返回長值的值,該值可以存儲比int大的整數,並且不能隱式轉換為int。
如果您將double
Math.Round
傳遞給Math.Round
那么結果將long
。
僅當您通過float
您才能得到一個int
結果。
從Java文檔中:
圓( 雙 )
返回最接近參數的long 。圓形( 浮點 )
返回與參數最接近的整數 。
根據Java文檔, Math.round(double)
將返回long
並且因為long
不是int
,因此必須使用(int)
進行(int)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.