float 與 double 問題:
- 專為科學和數學計算而設計,執行二元浮點運算。
- 不適合貨幣計算或需要精確答案的情況。
- 它們無法準確表示 10 的負冪,例如 0.1,這會導致錯誤。
範例1:
減去美元金額時計算錯誤:
System.out.println(1.03 - 0.42); // Resultado: 0.6100000000000001
範例2:
以每件 10 美分的價格購買 9 件商品時出錯:
System.out.println(1.00 - 9 * 0.10); // Resultado: 0.09999999999999998
即使四捨五入,錯誤仍然存在。
累進計算存在問題,例如以 0.10 到 1.00 的增量價格購買糖果時。
範例 3:
沒錢買糖果時犯的錯誤:
double funds = 1.00; for (double price = 0.10; funds >= price; price += 0.10) { funds -= price; } System.out.println(funds); // Resultado: 0.3999999999999999
解 1:使用 BigDecimal
- 非常適合財務計算和需要精確度的情況。
- 避免使用 BigDecimal 的雙重建構函數,最好使用 String 建構函數。
BigDecimal 範例:
BigDecimal funds = new BigDecimal("1.00"); BigDecimal price = new BigDecimal("0.10"); int itemsBought = 0; while (funds.compareTo(price) >= 0) { funds = funds.subtract(price); price = price.add(new BigDecimal("0.10")); itemsBought++; } System.out.println(itemsBought + " items bought. Money left: " + funds); // Resultado: 4 items bought. Money left: 0.00
計算現在很精確。
BigDecimal 的缺點:
- 使用起來不如原始型方便。
- 速度較慢,特別是對於大量操作。
解 2:使用 int 或 long
- 為了避免準確度問題,請使用 int 或 long 而不是 double 來以美分為單位進行計算。
int 範例(以分為單位):
int funds = 100; // 1.00 dólar = 100 centavos int price = 10; // 0.10 dólar = 10 centavos int itemsBought = 0; while (funds >= price) { funds -= price; price += 10; itemsBought++; } System.out.println(itemsBought + " items bought. Money left: " + funds); // Resultado: 4 items bought. Money left: 0
計算又快又準。
結論:
- 不要使用 float 或 double 進行需要精確精確度的計算。
- 使用 BigDecimal 進行貨幣計算或需要小數精度的情況。
- 使用 int 或 long 進行不涉及大數的金融計算,以分為單位進行計算。
選擇:
- 最多 9 位數字,請使用 int。
- 最多 18 位數字,請使用 long。
- 對於較大數量,請使用 BigDecimal。
- 此摘要表明,根據上下文,在 BigDecimal、int 或 long 之間進行選擇可以優化精度和效能。
以上是如果需要準確答案,請避免浮動和雙精度的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。

javaisnotirelyplatemententedduetojvmvariationsandnativecodinteinteration,butitlargelyupholdsitsitsworapromise.1)javacompilestobytecoderunbythejvm

thejavavirtualmachine(JVM)IsanabtractComputingmachinecrucialforjavaexecutionasitrunsjavabytecode,使“ writeononce,runanywhere”能力

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多態性、Lambda表達式、StreamsAPI、泛型和異常處理。 1.多態性讓不同類的對象可以作為共同基類的對象使用。 2.Lambda表達式使代碼更簡潔,特別適合處理集合和流。 3.StreamsAPI高效處理大數據集,支持聲明式操作。 4.泛型提供類型安全和重用性,編譯時捕獲類型錯誤。 5.異常處理幫助優雅處理錯誤,編寫可靠軟件。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具