关于浮点数出现在条件控制语句中的问题

今天修改程序,发现程序中有如下语句

其中条件控制语句中出现了两个浮点数相比较的情况。

记得MISRA中是明令禁止比较浮点数是否相等问题(此问题答案见C-FAQ Q14.5:http://c-faq.com/fp/fpequal.html),又禁止浮点数出现在for循环的条件控制语句上,因为浮点数比较结果会有不确定性,且会累积一些不确定的值。

 

那么是否能出现if语句的条件表达式中呢?

反正看着不舒服,就去网上找答案。

 

目前有两张方法,一个是将浮点数转换为“可以接受的精度”的定点数以后再进行比较。

比如二目运算符>,<两边同时左移10位(放大1024倍),嫌精度不够可以继续左移10位(放大1024*1024倍)。

即:

还有一种可以推荐的方法,我在misra的论坛上找到了。

其实它并没有回避浮点数比较,只是避免了不确定值的累积(没有验证)。

http://www.misra.org.uk/forum/viewtopic.php?f=69&t=873

 

问题:Rule 13.4 clarification

by Alexandre Langenieux » Mon Sep 01, 2008 4:38 pm

Dear Misra committee,

The rule 13.4 says:
The controlling expression of a for statement shall not contain any objects of floating type.

Does it apply only to loop counter, as suggest in the text explaining the rule ( ... floating-point variables shall not be used for this purpose [loop counter] ...). or to all operand of a controlling expression ?

I mean, can we consider the following for loop as compliant ?
回答:

by misra-c » Mon Sep 08, 2008 2:52 pm

Rule 13.4 states that no objects of floating point type may appear in the controlling expression (i.e. the 2nd expression) of a for statement.
Therefore, the example given in the question violates rule 13.4. The recommended method for introducing additional conditions into the controlling expression is to use a boolean flag. So, the example given could be re-written as:
Using a floating point object to count loop iterations is not recommended. For some values of the loop limits and increment, the accumulation of rounding errors could result in a number of iterations that differs from the expected number.

However, there are contexts in which use of floating point objects in a controlling expression might not cause any issues. MISRA-C:2004 does not permit any such other uses but MISRA will give due consideration to such contexts in a future version of the MISRA C rules. [ID0000010]
MISRA C Committee
看来只要是不用在循环的条件控制语句上就行!if的控制语句还是可以用的。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值