簡體   English   中英

如何找到浮點數的最短表示

[英]How can I find the shortest representation of a floating-point number

如果我嘗試為該類型打印具有最大精度的浮點值,例如:

printf("%.100e", FLT_MIN);

我明白了:

1.1754943508222875079687365372222456778186655567720875215087517062784172594547271728515625000000000000e-38

但是,如果我嘗試打印這樣的內容(我更改了尾數的最后一位):

float x = 1.1754943508222875079687365372222456778186655567720875215087517062784172594547271728515610e-38f;
printf("%.100e", x);

那么output也是一樣的:

1.1754943508222875079687365372222456778186655567720875215087517062784172594547271728515625000000000000e-38

這是因為我輸入的值沒有精確的表示,所以它被四舍五入了。

問題是:如何找到四舍五入到相同數字的最短值(以數字表示)?

您可以使用 C99 中引入的十六進制浮點數。

#include <stdio.h>

int main() {
    float x = 1.1754943508222875079687365372222456778186655567720875215087517062784172594547271728515625000000000000e-38;
    printf("%a\n", x); // prints 0x1p-126
    float hx = 0x1p-126;
    printf("%a\n", hx); // prints 0x1p-126
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM