关于C++builder中精度丢失的问题

来源:互联网 发布:通达信证券交易软件 编辑:程序博客网 时间:2024/05/21 06:56

原意:现有应交款项m元,折扣率n(0 < n < 1),折扣金额采取向下取整制,求折扣后金额LastMoney
公式:LastMoney = m - ( m * ( 1 - n ) )

现设m 为 14.25元  折扣率n为0.8 根据公式计算:
int nOrginMoney = 1425;(转换成分为单位进行计算)
double dRebate  = 0.8;

int tempMoney  = nOrginMoney * (1 - dRebate );
int nLastMoney = nOrginMoney - tempMoney ;

上面的做法存在精度丢失的问题,tempMoney 为整形,而等号右边的计算赋值得出的是浮点数,在进行转换的时候会对小数点后面进行截断。虽然这符合向下取整的规则,但是在上面的例子当中,右边 nOrginMoney * (1 - dRebate )算出来的是285.00,而转成Int类型之后放在tempMoney当中时,tempMoney的值为284,究其原因,右边的double计算值在内存当中进行存储的值并非285.00,而应该是284.9999XXXX,而这样直接进行强制转换会照成了精度的丢失。正确的类型转换并向下取整应该如下:

int tempMoney  = nOrginMoney * (100 - (int)(dRebate*100) ) / 100;
将折扣率进行放大并装换成Int进行计算,放大系数由折扣率的精度决定。
0 0
原创粉丝点击