JAVA-基礎資料類型轉換

來源:互聯網
上載者:User

package cn.zhao.base;</p><p>/**<br /> * 資料類型轉換<br /> * */<br />public class MyDemo<br />{<br />public static void main( String[] args )<br />{<br />//6個正常順序的類型轉換<br />// byte -> short<br />// short -> int<br />// int -> long<br />// char -> int<br />// int -> double<br />// float -> double </p><p>//3種可能會丟失精度的轉換<br />//int -> float<br />// long -> double<br />// long -> float</p><p>System.out.println( "當兩個數運算時,如果有一個是double,是將別一個也轉成double" ) ;<br />System.out.println( 3 + 3.0 ) ;</p><p>System.out.println( "當兩個數運算時,如果有一個是float,是將別一個也轉成float" ) ;<br />System.out.println( 3 + 3.0f ) ;</p><p>System.out.println( "當兩個數運算時,如果有一個是long,是將別一個也轉成long" ) ;<br />System.out.println( 3l + 3 ) ;</p><p>System.out.println( "否則,2個數都將被轉換成為int,很明顯,結果不對,是因為200超出byte範圍,丟失精度") ;<br />System.out.println( 100 + (byte)200 ) ;</p><p>System.out.println( "------------------強制類型轉換-----------------" ) ;<br />System.out.println( "double向int強轉") ;<br />double num = 300.5 ;<br />int intNum = (int) num ;<br />System.out.println( intNum ) ;<br />//結果是300,小數向整數強轉就是將小數部分去掉。<br />//如果想要精確轉換,要以使用四捨五入<br />int intNumRound = (int) Math.round( num ) ;<br />System.out.println( intNumRound ) ;//301<br />}<br />}<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.