主流架构(gcc、msvc、x86、x64、arm)中double与float浮点数保留精度(末尾清零)

​​​​​​float 是单精度浮点数,内存占4个字节,有效数字8位,表示范围是 -3.40E+38~3.40E+38。

double 是双精度浮点数,内存占8个字节,有效数字16位,表示范是-1.79E+308~-1.79E+308。

    C和C++标准没有指定EDCOX1、1、EDCOX1、0和EDCOX1×9的表示。这三个都有可能实现为IEEE双精度。然而,对于大多数架构(gcc、msvc、x86、x64、arm),float实际上是一个IEEE单精度浮点数(binary32),double是一个IEEE双精度浮点数(binary64)。

    有时甚至double也不够精确,因此有时我们有long double1(上面的例子在Mac上给出了9.00000000000000066),但所有浮点类型都有舍入错误,因此,如果精度非常重要(例如,货币处理),则应使用int或分数类。

    浮点会由于精度问题,导致无法直接做 != 比较,下面是一个主流架构下,优化处理浮点精度的函数:

#include <cmath>

// fVal		原始浮点
// iPoint	保留精度(末尾将清零)
double getVal1(const double fVal, const int iPoint) {
    double factor = pow(10.0, iPoint);
    return floor(fVal * factor) / factor;
}

double getVal2(const double fVal, const int iPoint) {
    double factor = pow(10.0, iPoint);
    return round(fVal * factor) / factor;
}

double getVal3(const double fVal, const int iPoint) 
{
	double	multiplier = 1.0;
	int 	i;
	
	// Calculate the multiplier based on the number of decimal places to keep
	for (i = 0; i < iPoint; i++) {
		multiplier *= 10.0;
	}
	
	// Multiply the original value by the multiplier and round it to the nearest integer
	int roundedValue = (int)(fVal * multiplier + 0.5);
	
	// Divide the rounded value by the multiplier to get the final result
	double result = roundedValue / multiplier;
	
	return result;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汪宁宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值