国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

Java_一個(gè)有趣的重載函數(shù)栗子

2019-11-06 07:12:17
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

今天主要想討論一下C++時(shí)我就很迷糊的重載函數(shù)的概念

java是支持重載的,我們通過(guò)一個(gè)簡(jiǎn)單的栗子來(lái)看一下它的機(jī)制

package float_or_double;public class FloatOrDouble { public static void aMethod(int a){ System.out.可以看到,我聲明了4個(gè)重載函數(shù),每一個(gè)對(duì)應(yīng)的形參都不同,分別為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)制描述。

有趣的是,當(dāng)我刪去形參為int的重載函數(shù)后,如果數(shù)字后面沒有小數(shù)點(diǎn),則將自動(dòng)解釋為float類型

代碼如下

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


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 内丘县| 枣庄市| 乌什县| 白城市| 肇东市| 元阳县| 嵊泗县| 久治县| 玉龙| 商洛市| 延川县| 柞水县| 都昌县| 宣城市| 广德县| 班戈县| 无棣县| 内黄县| 大名县| 云阳县| 磐石市| 九寨沟县| 内乡县| 灵石县| 三门县| 公主岭市| 华池县| 沙坪坝区| 玛沁县| 红河县| 美姑县| 乌苏市| 阿城市| 渑池县| 宣城市| 米林县| 河东区| 南和县| 万年县| 右玉县| 申扎县|