簡體   English   中英

為什么在使用 printf float 和 double 時顯示相同的位數?

[英]Why when using printf float and double show the same number of digits?

我想看看使用 float 和使用 double 時我得到的位數有多少不同,但我得到了相同的結果

#include <stdio.h>

int main()
{
    float x=1.2222222222222222f;
    printf("%f %d", x,sizeof(x)); // This is what it prints out 1.222222 4
    return 0;
}
#include <stdio.h>

int main()
{
    double x=1.2222222222222222;  
    printf("%f %d", x,sizeof(x));  // This is what it prints out 1.222222 8
    return 0;
}

它打印出相同的值,即使 double 顯然是大小的兩倍並且應該保存更多數字。 我究竟做錯了什么?

sizeof返回size_t 要打印size_t你需要%zu而不是%d

如果您想查看floatdouble之間的真正區別,您需要使用%.NUMBERf打印更多數字

喜歡:

#include <stdio.h>

int main(void)
{
    float x=1.2222222222222222f;
    printf("%.70f %zu\n", x,sizeof(x)); 
    double y=1.2222222222222222;  
    printf("%.70f %zu\n", y,sizeof(y)); 
    return 0;
}

Output:

1.2222222089767456054687500000000000000000000000000000000000000000000000 4
1.2222222222222220988641083749826066195964813232421875000000000000000000 8

它打印出相同的值,即使 double 顯然是大小的兩倍並且應該保存更多數字。

printf()中將float作為...參數傳遞時,它首先被提升為double "%f"double打印到 . 之后的 6 位. .

由於四舍五入到小數點后 6 位時原始值沒有差異,因此它們看起來相同。

我究竟做錯了什么?

期望默認精度 6 不足以區分。


使用"%a"最容易看出不同。

printf("%a\n", 1.2222222222222222);
printf("%a\n", 1.2222222222222222f);

0x1.38e38e38e38e3p+0
0x1.38e38ep+0

或以指數表示法有足夠的小數位。

printf("%.*e\n", DBL_DECIMAL_DIG - 1, 1.2222222222222222);
printf("%.*e\n", DBL_DECIMAL_DIG - 1, 1.2222222222222222f);

1.2222222222222221e+00
1.2222222089767456e+00

暫無
暫無

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

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