08-float和double

本文详细探讨了float和double两种浮点数类型的内存占用差异,通过实例验证了它们在精度上的具体表现,展示了在不同精度设置下数值的细微变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

float和double的区别

这两个浮点类型经常进行使用,但是两者的区别一直进行混淆,通过本文来记录一下。

首先来记录一个最基本的概念

byte和bit

英文中文转换
byte字节8bit
bit1 bit

bit是计算机最小单位。

double和float

在内存中占有的字节数不同

数据类型所占空间
单精度浮点数 float4byte
双精度浮点数 double8byte

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

以上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值