float和double的区别
这两个浮点类型经常进行使用,但是两者的区别一直进行混淆,通过本文来记录一下。
首先来记录一个最基本的概念
byte和bit
英文 | 中文 | 转换 |
---|---|---|
byte | 字节 | 8bit |
bit | 位 | 1 bit |
bit是计算机最小单位。
double和float
在内存中占有的字节数不同
数据类型 | 所占空间 |
---|---|
单精度浮点数 float | 4byte |
双精度浮点数 double | 8byte |
demo 解释验证
demo.cpp
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
float a = 2.3;
double b = 2.3;
cout << "float is " << sizeof(a) << " byte" << endl;
cout << "double is " << sizeof(b) << " byte" << endl;
printf("set 7 point a = %.7f\n", a);
printf("set 8 point a = %.8f\n", a);
printf("set 15 point b = %.15f\n", b);
printf("set 16 point b = %.16f\n", b);
return 0;
}
输出结果
float is 4 byte
double is 8 byte
set 7 point a = 2.3000000
set 8 point a = 2.29999995
set 15 point b = 2.300000000000000
set 16 point b = 2.2999999999999998
通过这个demo也验证了上述的理论
环境raspberry pi ubuntu service 64bit
➜ cpp lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 18.04.2 LTS
Release: 18.04
Codename: bionic
以上