int,float,double,char程序輸出結(jié)果為
a=3.5 and is the double one!a=3.5 and is the double one!a=3.0 and is the double one!a=3.0 and is the double one!a=3.0 and is the float one!a=3 and is the int one!a=c and is the char one!Java將數(shù)字后面有小數(shù)點(diǎn)的統(tǒng)一解釋為double,而要想調(diào)用形參為float的需要在數(shù)字后面注明’f’
查找資料后得知: 對(duì)編程人員來(lái)說(shuō),double 和 float 的區(qū)別是double精度高,有效數(shù)字16位,float精度7位。但double消耗內(nèi)存是float的兩倍,double的運(yùn)算速度比f(wàn)loat慢得多,java語(yǔ) 言中數(shù)學(xué)函數(shù)名稱double 和 float不同,不要寫錯(cuò),能用單精度時(shí)不要用雙精度(以省內(nèi)存,加快運(yùn)算速度)
(1)float型 內(nèi)存分配4個(gè)字節(jié),占32位,范圍從10^-38到10^38 和 -10^38到-10^-38 例float x=123.456f,y=2e20f; 注意float型定義的數(shù)據(jù)末尾必須有”f”或”F”,為了和double區(qū)別
(2)double型 內(nèi)存分配8個(gè)字節(jié),范圍從10^-308到10^308 和 -10^-308到-10^-308 例double x=1234567.98,y=8980.09d; 末尾可以有”d”也可以不寫
單精度浮點(diǎn)數(shù)在機(jī)內(nèi)占4個(gè)字節(jié),用32位二進(jìn)制描述。 雙精度浮點(diǎn)數(shù)在機(jī)內(nèi)占8個(gè)字節(jié),用64位二進(jìn)制描述。
代碼如下
package float_or_double;public class FloatOrDouble { /*public static void aMethod(int a){ System.out.println("a="+a+" and is the int one!"); }*/ public static void aMethod(float a){ System.out.println("a="+a+" and is the float one!"); } public static void aMethod(double a){ System.out.println("a="+a+" and is the double one!"); } public static void aMethod(char a){ System.out.println("a="+a+" and is the char one!"); } public static void main(String args[]){ aMethod(3.5); aMethod(3.50); aMethod(0.0); aMethod(0); aMethod(0.); aMethod(3d); aMethod(3f); aMethod(3); aMethod('c'); }}輸出結(jié)果為
a=3.5 and is the double one!a=3.5 and is the double one!a=0.0 and is the double one!a=0.0 and is the float one!a=0.0 and is the double one!a=3.0 and is the double one!a=3.0 and is the float one!a=3.0 and is the float one!a=c and is the char one!一個(gè)小彩蛋,Java中char類型是可以參與運(yùn)算的,如將形參為char的重載函數(shù)改為如下形式:
public static void aMethod(char a){ System.out.println("a="+(a+1)+" and is the char one!"); }那么會(huì)輸出a=100 and is the char one!,可以看到,’c’參與到了計(jì)算中,結(jié)果為ascii碼+1
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注