C's float and double precision? [duplicate]

蓝咒 提交于 2019-12-11 16:56:53

问题


I recently found this C code online.

#include <stdio.h>

int main() {
    double x = 3.1;
    float y = 3.1;

    if(x==y)
        printf("yes");
    else
        printf("No");
}

The output is No.

I added a few more printf calls to investigate

#include <stdio.h>

int main() {
    double x = 3.1;
    float y = 3.1;

    if(x==y)
        printf("yes");
    else
        printf("No");

    printf("%.10f\n", y);
    printf("%.10f\n", x);

    return 0;
}

The output came as

3.0999999046
3.1000000000

Why is it so? Why has the float variable lost its precision when printed to 10 decimal places?

来源:https://stackoverflow.com/questions/48866943/cs-float-and-double-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!