浮点数的范围与精度

1 浮点数在内存中分配的空间大小

在LeetCode的编译环境下:

float:4字节(32位)

double:8字节(64位)

2 浮点数的精度

测试1:

#include <stdio.h>

int main(void)
{
    float a = 1.23456789123456789123;
    double b = 1.23456789123456789123;
    printf("a = %.20f
",a);
    printf("b = %.20f
",b);
}

输出结果如下:

a = 1.23456788063049320
b = 1.23456789123456790
Press any key to continue

测试2:

#include <stdio.h>

int main(void)
{
    float a = 1223456.789123456789123;
    double b = 1223456.789123456789123;
    printf("a = %.20f
",a);
    printf("b = %.20f
",b);
}

输出结果如下:

a = 1223456.75000000000000000000
b = 1223456.78912345670000000000
Press any key to continue

测试3:

#include <stdio.h>

int main(void)
{
    float a = 3.14159265358979323846264338327950288419716939937510;
    double b = 3.14159265358979323846264338327950288419716939937510;
    printf("a = %.20f
",a);
    printf("b = %.20f
",b);
}

输出结果如下:

a = 3.14159274101257320000
b = 3.14159265358979310000
Press any key to continue

测试4:

#include <stdio.h>

int main(void)
{
    float a = 1.111111111111111111111111111;
    double b = 1.111111111111111111111111111;
    printf("a = %.20f
",a);
    printf("b = %.20f
",b);
}

输出结果如下:

a = 1.11111116409301760000
b = 1.11111111111111120000
Press any key to continue

测试5:

#include <stdio.h>

int main(void)
{
    float a = 12345678912;
    double b = 12345678912;
    printf("a = %.20f
",a);
    printf("b = %.20f
",b);
}

测试结果如下:

a = 12345678848.00000000000000000000
b = 12345678912.00000000000000000000
Press any key to continue

从上述测试结果看,浮点数表示一个数是有很大误差的,但double型比float型精度高。

3 浮点数的表示

以float为例,浮点数的表示如下图所示。

-314.16在内存中的存储方式如下图所示:

小数位:用23位二进制表示3.1416

二进制表示十进制小数的方法:

比如0.65换算成二进制就是:

0.65 × 2 = 1.3 取1,留下0.3继续乘二取整

0.3 × 2 = 0.6 取0, 留下0.6继续乘二取整

0.6 × 2 = 1.2 取1,留下0.2继续乘二取整

0.2 × 2 = 0.4 取0, 留下0.4继续乘二取整

0.4 × 2 = 0.8 取0, 留下0.8继续乘二取整

0.8 × 2 = 1.6 取1, 留下0.6继续乘二取整

0.6 × 2 = 1.2 取1,留下0.2继续乘二取整

.......

一直循环,直到达到精度限制才停止(所以,计算机保存的小数一般会有误差,所以在编程中,要想比较两个小数是否相等,只能比较某个精度范围内是否相等。)。这时,十进制的0.65,用二进制就可以表示为:0.1010011。

存储方式决定了浮点数的精度与范围:

4 参考

计算概论与程序设计基础-C语言中的数据成分-浮点型-李戈

https://www.icourse163.org/learn/PKU-1002529002?tid=1450221458#/learn/content?type=detail&id=1229624056&cid=1246839110

二进制后面的小数点怎么算?

https://zhidao.baidu.com/question/59125997.html

原文地址:https://www.cnblogs.com/QQ2962269558/p/12862618.html