java default parameter_JAVA菜鳥入門(7) default parameter , float/double vs BigDecimal

1 ?java的允許函數的默認參數嗎?

java不支持類似C++那樣,為函數設定默認參數,所以需要做的事情是,自己用函數重載的方式進行模擬。如下

public class FFOverload {

public String getName(String givenName,String familyName){

return givenName+"."+familyName;

}

public String getName(String givenName){

return getName(givenName,"BBB");

}

public static void main(String[] args) {

FFOverload demoDefaultPara=new FFOverload();

System.out.println(demoDefaultPara.getName("AAA"));

System.out.println(demoDefaultPara.getName("AAA", "CCC"));

}

}

輸出:

AAA.BBB

AAA.CCC

2. ?為什么floating point number不準確

首先來驗證一下

public class FloatTest {

public static void main(String[] args) {

float a = 1.01f; //don't forget the trailing 'f' , else it will be treated as a double.

float b = 1.002f;

float c = 1.0000009f;

float d = a + b + c;

System.out.println("expected: 3.0120009, actua: "+ d);

}

}

輸出:

expected: 3.0120009, actua: 3.012001

然后來看看原因:

In most programming languages, floating point numbers are represented a lot like scientific notation:

with an exponent and

a mantissa (also called the significand).

A very simple number, say 9.2, is actually this fraction:

5179139571476070 * 2 -49

Where the exponent is -49 and the mantissa is 5179139571476070.

The reason it is impossible to represent some decimal numbers this way is that both the exponent and the mantissa must be integers. In other words, all floats must be an integer multiplied by an integer power of 2.

Floating point numbers only have 32 or 64 bits of precision, so the digits are cut off at some point, and the resulting number is 0.199999999999999996 in decimal, not 0.2.

3. 如何盡可能準確地表示Floating Point Numbers?

3.1 使用BigDecimal Class

but currently there is a small unsolved issue in the code below. I did not see the difference between HALF_UP and HALF_DOWN in the code below.

import java.math.*;

public class FFBigDecimal {

public static void main(String[] args) {

BigDecimal bigDecimal1 = new BigDecimal(1.001);

BigDecimal bigDecimal2 = new BigDecimal(1.0005);

BigDecimal bigDecimal3 = new BigDecimal(1.000007);

BigDecimal bigDecimaBase = new BigDecimal(2.52150);

BigDecimal bigDecimal4 = bigDecimaBase.setScale(3, RoundingMode.HALF_DOWN);

System.out.println("Big Decimal is " + bigDecimal4.toString());

BigDecimal bigDecimal5 = bigDecimaBase .setScale(3, RoundingMode.HALF_UP);

System.out.println("Big Decimal is " + bigDecimal5.toString());

}

}

輸出

Big Decimal is 2.521

Big Decimal is 2.522

why???? ?I expected:

2.521

2.522

HALF_UP的定義是這樣的:

“Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for RoundingMode.UP if the discarded fraction is ≥ 0.5; otherwise, behaves as for RoundingMode.DOWN. Note that this is the rounding mode commonly taught at school.”

后來終于知道了原因,算是比較坑爹了。

BigDecimal的構造函數需要用String作為參數,否則將會出現一些比較奇怪的結果。所以上面的程度如果修改為:

import java.math.*;

public class FFBigDecimal {

public static void main(String[] args) {

BigDecimal bigDecimal1 = new BigDecimal("1.001");

BigDecimal bigDecimal2 = new BigDecimal("1.0005");

BigDecimal bigDecimal3 = new BigDecimal("1.000007");

//test 1

//bigDeciimal3 is immutable, so

// WRONG: bigDecimal3.add(bigDecimal1).add(bigDecimal2);

// CORRECT: bigDecimal3 = bigDecimal3.add(bigDecimal1).add(bigDecimal2);

bigDecimal3 = bigDecimal3.add(bigDecimal1).add(bigDecimal2);

BigDecimal bigDecimaBase = new BigDecimal("2.52150");

BigDecimal bigDecimal4 = bigDecimaBase.setScale(3, RoundingMode.HALF_DOWN);

System.out.println("Big Decimal is " + bigDecimal4.toString());

BigDecimal bigDecimal5 = bigDecimaBase .setScale(3, RoundingMode.HALF_UP);

System.out.println("Big Decimal is " + bigDecimal5.toString());

}

}

就是符合預期的,得到的輸出結果將是:

Big Decimal is 2.521

Big Decimal is 2.522

3.2 如果在Double和Float中二選一,選擇Double.

Double (8 位)

Float (4 位)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/541872.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/541872.shtml
英文地址,請注明出處:http://en.pswp.cn/news/541872.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

gitlab修改默認端口

部署gitlab的時候,一啟動,發現80和8080端口已經被占用,無奈,只得先將監聽80端口的nginx和監聽8080端口的jenkins停止。這會兒有空,琢磨一下如何修改gitlab的默認端口。 修改主要分為兩部分,一部分是gitlab總…

Java ObjectOutputStream reset()方法與示例

ObjectOutputStream類reset()方法 (ObjectOutputStream Class reset() method) reset() method is available in java.io package. reset()方法在java.io包中可用。 reset() method is used to reset this stream. It reset the stream to the position marked most recently. …

Excel 自定義關閉按鈕

遇到過這樣一個需求,是在excel關閉的時候,不要excel本身的保存窗口,只用自定義的. 這個的需要第一,是點擊關閉時候觸發, 第二;觸發后,不能還是彈出那個窗口 第三:取消后,…

Java OutputStreamWriter close()方法與示例

OutputStreamWriter類close()方法 (OutputStreamWriter Class close() method) close() method is available in java.io package. close()方法在java.io包中可用。 close() method is used to first flush before closing the stream and the method write() or flush() invok…

深入理解Netscaler INat

深入理解Netscaler INatNetscaler的INat主要是用作基于目的地址的轉換,將client訪問的公網IP通過Netscaler轉換成服務器的私網IP,與DNAT作用類似。由于Netscaler默認的工作機制就是同時做源IP:【源端口】目的IP:【目的端口】的轉換…

java 方法 示例_Java語言環境getDisplayCountry()方法與示例

java 方法 示例區域設置類getDisplayCountry()方法 (Locale Class getDisplayCountry() method) Syntax: 句法: public final String getDisplayCountry();public String getDisplayCountry(Locale lo);getDisplayCountry() method is available in java.util pack…

格力電器Java面試題_JAVA設計模式學習--工廠模式

今天談一下對工廠模式學習的總結。看完視頻和文章之后要自己表述工廠模式,總是感覺無從說起,不知道怎么去定義工廠模式,反復看了幾遍之后終于理解一點。自己理解工廠模式是通過這兩種模式的特點來理解和定義的,首先工廠模式有簡單…

為什么玩我的世界老提示Java se錯誤_我的世界error錯誤信息 error could解決方法

我的世界是一個及其開放的沙盒游戲,而在這個游戲中有不少的問題,比如說遇到error該如何解決呢,看小編給大家帶來的我的世界error錯誤的解決方法,希望大家喜歡。error應用程序錯誤信息。包括“Error:Unable to access jarfile mcpc…

Tomcat 服務器只能存有一個正在運行的項目

即使新建了一個new project (在同一個工作空間),啟動Tomcat 還是會出現先前(工程名)一樣的問題/異常。 【原因】: 在底下Server 那里——Tomcat 7.X 底下會有很多工程名,它會紀錄!所…

Java Collections singletonMap()方法與示例

集合類singletonMap()方法 (Collections Class singletonMap() method) singletonMap() method is available in java.util package. singletonMap()方法在java.util包中可用。 singletonMap() method is used to return an immutable map (i.e. immutable map is a map that c…

java訪問登錄網頁_===java怎樣訪問需要登錄才能查看的網頁????急!!===...

java中可以用java.net包下的東西訪問網頁,但是有的網頁要求用戶先輸入用戶名和密碼才能查看,這些網頁java怎么訪問呢???注意:我說的要輸入用戶名和密碼不是瀏覽器彈出一個框的那種,而是象csdn這…

javascript OOP(下)(九)

一、javascript模擬重載 java中根據參數類型和數量的區別來實現重載&#xff0c;javascript弱類型&#xff0c;沒有直接的機制實現重載&#xff0c;javascript中參數類型不確定和參數個數任意&#xff0c;通過判斷實際傳入的參數的個數來實現重載。 <script> function Pe…

java calendar_Java Calendar getDisplayNames()方法與示例

java calendar日歷類的getDisplayNames()方法 (Calendar Class getDisplayNames() method) getDisplayNames() method is available in java.util package. getDisplayNames()方法在java.util包中可用。 getDisplayNames() method is used to return Map that contains all fie…

Linux如何查找大文件或目錄總結

轉載&#xff1a;http://www.cnblogs.com/kerrycode/p/4391859.html 在Windows系統中&#xff0c;我們可以使用TreeSize工具查找一些大文件或文件夾&#xff0c;非常的方便高效&#xff0c;在Linux系統中&#xff0c;如何去搜索一些比較大的文件呢&#xff1f;下面我整理了一下…

java編寫簡單郵件_Javamail,編寫簡單的程序發送郵件

代碼&#xff1a;package com.dai.mail; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.In…

java calendar_Java Calendar getLeastMaximum()方法與示例

java calendarCalendar類的getLeastMaximum()方法 (Calendar Class getLeastMaximum() method) getLeastMaximum() method is available in java.util package. getLeastMaximum()方法在java.util包中可用。 getLeastMaximum() method is used to get the least maximum value …

Shell 標準輸入、輸出和錯誤

防偽碼&#xff1a;桃花潭水深千尺&#xff0c;不及汪倫送我情。文件描述符&#xff08;fd&#xff09;&#xff1a;文件描述符是一個非負整數&#xff0c;在打開現存文件或新建文件時&#xff0c;內核會返回一個文件描述符&#xff0c;讀寫文件也需要使用文件描述符來訪問文件…

java需要會的工具_Java開發者必備的幾款工具,一定要掌握!

原標題&#xff1a;Java開發者必備的幾款工具&#xff0c;一定要掌握&#xff01;NotepadNotepad是用于編輯xml、腳本以及記筆記的最佳工具。這個工具的最好部分在于&#xff0c;你在Notepad上打開的任何一個文檔&#xff0c;在關閉后都會有一個殘留文檔&#xff0c;它有助于在…

java的equals方法_Java LocalDateTime類| 帶示例的equals()方法

java的equals方法LocalDateTime類equals()方法 (LocalDateTime Class equals() method) equals() method is available in java.time package. equals()方法在java.time包中可用。 equals() method is used to check whether this date-time and the given object are equal or…

portlet java_Java Portlet 規范概述

前言1、portlet是一種類似servlet的規范。2、servlet是web組件&#xff0c;portlet也是web組件。參考1、百度百科&#xff1a;portlethttp://baike.baidu.com/link?urlvMzVwpkf5WzOL23GLkgM4C5C7Sarqh1XXShS73L7k-MbGgM0ooZ4Dl2Efor3bb4tZmmLo6v-muG5UW7_CYMTUahttp://hintcnu…