|
|
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已! |
|
恭喜您是本站第 1734039
位訪客!
登入 | 註冊
|
|
|
|
發表者 |
討論內容 |
冷日 (冷日) |
發表時間:2009/8/10 15:23 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15773
|
- Re: [自創]測試Java的四捨五入、無條件捨去、無條件進位
- 1.冷日不是大大...
2.這個問題應該是給Compiler告訴你答案最快ㄚ!?
冷日就直接寫了一個測試:
/* ========================================================================== */
/* ========================================================================== */
/* TestRound2.java
/* (c) 2009 Author 冷日
/* Description
/* 網站上有人問 double i=100.22 , j=32.33 , k=Math.round(i*j);
/* 那會做如何的計算?取第幾位呢?如果k要四捨五入到小數點第一位該做怎樣的處理呢?
/* ========================================================================== */
import java.io.*;
import java.lang.*;
class TestRound2 {
public static void main(String[] args) {
double i , j , k , l , m , n;
i = 100.24;
j = 32.33;
k = ( i * j ) ;
l = Math.round( k );
m = Math.round( k * 100 );
n = m / 100 ;
System.out.println("k is : " + k);
System.out.println("l is : " + l);
System.out.println("m is : " + m);
System.out.println("n is : " + n);
}
}
然後下去跑結果來看:
---------- Run ----------
k is : 3240.7591999999995
l is : 3241.0
m is : 324076.0
n is : 3240.76
輸出完成 (耗費 0 秒)。 - 正常結束
Java清楚的告訴我們答案: 1.如何的計算!?當然是四捨五入啦! 2.看起來預設取第一位(準確一點的資料要去查JDK)! 引言:round public static long round(double a)Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)Special cases:
If the argument is NaN, the result is 0. If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE. If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.
Parameters: a - a floating-point value to be rounded to a long. Returns: the value of the argument rounded to the nearest long value. See Also: Long.MAX_VALUE, Long.MIN_VALUE
3.小數點第一位的話,預設就是,不然還有另一個技巧,就是乘上你要留的位數再除上該十進位數(EX:如果要保留三位小數,乘1000再除1000就行)
最後,程式這東西ㄚ,寫就對了,Compiler一定會告訴你答案低! 
|
|
討論串
|