C语言中关键字double,float的包含范围与注意事项

思考以下程序:

#include <stdio.h>
const double DELTA=1e-9;     //意为1乘10的-9次方,这是浮点数表示方式
int main()
{
    
    
    int x,y;
    double f=0.0006;

    x=(int)(f*10000);
    printf("%d\n",x);

    y=(int)((f+DELTA)*10000);
    printf("%d\n",y);

    getchar();
    return 0;
}
//为什么输出结果为5,6.

我们需要明白一点,就是float,double的字节数以及小数点后的精度不同。

关键字 字节数 数值范围
float 4 ±3.4E±38(精确6到7位数)
double 8 ±1.7E±308(精确到15个数)
long 12 ±1.9E±4932(精确到18位小数)

将double换成float后:

#include <stdio.h>
const double DELTA=1e-9;          
int main()
{
    
    
    int x,y;
    float f=0.0006;

    x=(int)(f*10000);
    printf("%d\n",x);

    y=(int)((f+DELTA)*10000);
    printf("%d\n",y);

    getchar();
    return 0;
}
//结果为6,6

此外,注意浮点数表示的是精确值,假如显示的是1.0,计算机中可能是0.9999999或者1.000000001。不同的操作系统,相同的数据长度类型长度可能有差异。

猜你喜欢

转载自blog.csdn.net/weixin_51871724/article/details/112205742