主流架构(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;
}

猜你喜欢

转载自blog.csdn.net/wangningyu/article/details/133998359
今日推荐