日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

为什么java中floatda正确_为什么cast to float在java中产生正确的结果?

發布時間:2024/8/23 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 为什么java中floatda正确_为什么cast to float在java中产生正确的结果? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文檔沒有特別好地解釋,但

Double.toString(double)基本上在它產生的輸出中執行一些舍入. Double.toString算法在整個Java SE中使用,包括例如System.out的PrintStream.println(double).文檔說明了這一點:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part,and beyond that as many,but only as many,more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is,suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x,then d must be one of them and the least significant bit of the significand of d must be 0.

換句話說,它表示toString的返回值不一定是參數的精確十進制表示.唯一的保證是(粗略地說)參數比任何其他雙值更接近返回值.

因此,當您執行類似System.out.println(1.10)和1.10的操作時,這并不意味著傳入的值實際上等于基數10值1.10.相反,基本上會發生以下情況:

>首先,在編譯期間,檢查文字1.10并舍入以產生最接近的double值. (它在JLS here中說,對此的規則例如在Double.valueOf(String)中詳細說明為double.)

>其次,當程序運行時,Double.toString生成一個十進制值的字符串表示形式,上一步生成的double值比任何其他double值更接近.

恰好在第二步中轉換為String通常會生成一個與第一步中的文字相同的String.我認為這是設計的.無論如何,文字,例如1.10不會產生一個精確等于1.10的雙精度值.

您可以使用BigDecimal(double)構造函數發現double(或float的實際值,因為它們總是可以放在double中):

When a double must be used as a source for a BigDecimal,note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result,use the static valueOf(double) method.

// 0.899999999999999911182158029987476766109466552734375

System.out.println(new BigDecimal((double) ( 2.00 - 1.10 )));

// 0.89999997615814208984375

System.out.println(new BigDecimal((float) ( 2.00 - 1.10 )));

你可以看到,結果都不是0.9.在這種情況下,Float.toString恰好產生0.9而Double.toString則不然,這或多或少只是巧合.

作為旁注,(雙)(2.00 – 1.10)是一個冗余演員. 2.00和1.10已經是雙重文字,因此評估表達式的結果已經是雙倍的.另外,要減去float,你需要轉換兩個操作數,如(float)2.00 – (float)1.10或使用浮動文字,如2.00f – 1.10f. (float)(2.00 – 1.10)僅將結果轉換為float.

總結

以上是生活随笔為你收集整理的为什么java中floatda正确_为什么cast to float在java中产生正确的结果?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。