为什么这种方法仍然会对货币产生舍入错误?

Gre*_*lty 1 c math floating-point rounding-error

这是代码:

float accountBalance = 0; //global

//this function gets called many times  
int Accumulate(float amount) //amount in currency form, i.e. xxx.yy
{
   float fixroundVal = 0;

   amount = amount * 100; //change to full number (removes decimals)

   accountBalance += amount;

   fixroundVal = accountBalance / 100;

   printf("fixroundVal=%f",fixroundVal);//really gets stored   

}
Run Code Online (Sandbox Code Playgroud)

所以之前,我没有fixroundVal值和缩放100 - 它只是 accountBalance += amount;

我得到了非常糟糕的舍入错误,因此我每次迭代都进行了 100次本地缩放,并且它消除了很多舍入错误但是偶尔会有一些,我仍然会得到一些.

我尝试将100比例增加到10的其他倍数,实际上我有更多的舍入错误.

我只能使用C,没有库.

我怎样才能解决这个问题?

(更尊重银行软件;)

mcl*_*sen 7

这是因为当您将结果除以100时,您仍在进行浮点除法并将结果存储在浮点表示中.浮点数只能通过使用二进制的分数来近似.你必须得到1/2 1/4 1/8等与实际实际值的最接近的总和.例如0.2的某些数字不能在浮点中精确表示.

解决方案是将美元金额表示为整个系统中整数的分数.那么你可以完全代表20美分.

  • 另外:要打印出以美分存储的货币值,您可以通过执行以下操作来避免转换为浮动(假设您知道金额为正数):`printf("%d.02d",金额/ 100,金额%100 );` (3认同)