Một ví dụ khá hay giúp ta hiểu rõ hơn về cách sử dụng phương thức Math.round để làm tròn số trong ngôn ngữ lập trình Java.
Mã nguồn - Source Code
/**
* @(#)RoundDoubles.java
*
* RoundDoubles application
*
* @author Bui Ngoc Son
* @website vnlives.net
* @version 1.00 2014/6/21
*/
public class RoundDoubles {
public static void main(String[] args) {
double pi = 3.14159265359;
System.out.println(pi);
System.out.println("-----------------------------");
System.out.println( Math.round(pi) );
System.out.println( (double)Math.round(pi*10)/10 );
System.out.println( (double)Math.round(pi*100)/100 );
System.out.println( (double)Math.round(pi*1000)/1000 );
System.out.println( (double)Math.round(pi*10000)/10000 );
System.out.println( (double)Math.round(pi*100000)/100000 );
System.out.println( (double)Math.round(pi*1000000)/1000000 );
System.out.println( (double)Math.round(pi*10000000)/10000000 );
}
}
* @(#)RoundDoubles.java
*
* RoundDoubles application
*
* @author Bui Ngoc Son
* @website vnlives.net
* @version 1.00 2014/6/21
*/
public class RoundDoubles {
public static void main(String[] args) {
double pi = 3.14159265359;
System.out.println(pi);
System.out.println("-----------------------------");
System.out.println( Math.round(pi) );
System.out.println( (double)Math.round(pi*10)/10 );
System.out.println( (double)Math.round(pi*100)/100 );
System.out.println( (double)Math.round(pi*1000)/1000 );
System.out.println( (double)Math.round(pi*10000)/10000 );
System.out.println( (double)Math.round(pi*100000)/100000 );
System.out.println( (double)Math.round(pi*1000000)/1000000 );
System.out.println( (double)Math.round(pi*10000000)/10000000 );
}
}
Kết quả - Result
No comments:
Post a Comment