在浮点坏样式上使用increment(operator ++)? [英] Is using increment (operator++) on floats bad style?

查看:177
本文介绍了在浮点坏样式上使用increment(operator ++)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浮动上使用增量运算符(++)是否被认为是坏风格?

Is it considered "bad style" to use the increment operator (++) on floats? It compiles just fine but I find it smelly and counter-intuitive.

问题:在什么情况下使用 ++ on float variable justised and better than + = 1.0f ?如果没有用例,是否有一个相当可观的C ++风格指南,明确说明float上的++是邪恶的?

The question: In what cases is using ++ on float variable justified and better than += 1.0f? If there are no use cases, is there a respectable C++ style guide that explicitly says that ++ on float is evil?

对于float ++,有效值,但为1.0。 1.0f没有特殊含义(与整数1不同)。它可能会混淆读者,使他认为变量是int。

For float ++ does not increment by the smallest possble value, but by 1.0. 1.0f has no special meaning (unlike integer 1). It may confuse the reader causing him to think that the variable is int.

对于float,不保证operator ++改变参数。例如下面的循环不是无限的:

For float it is not guaranteed that operator++ changes the argument. For example the following loop is not infinite:

float i, j;
for (i=0.0, j=1.0; i!=j;i=j++);

因此在之后立即执行++ - 不保证该值不变。

Consequently doing ++ immediately after -- does not guarantee that the value is unchanged.

推荐答案

通常 ++ / - 因为它不清楚浮点值应该增加哪个值。所以,你可能在一个系统上运气, ++ 导致 f + = 1.0f 但可能有情况其中这是无效的。因此,对于浮动,您必须提供一个特定的值。

In general ++/-- is not defined for floats, since it's not clear with which value the float should be incremented. So, you may have luck on one system where ++ leads to f += 1.0f but there may be situations where this is not valid. Therefore, for floats, you'll have to provide a specific value.

++ / - 被定义为增加/减少1。因此,这适用于浮点值。但是,我个人认为,这可能是混淆的人不知道这个定义(或只适用于整数),所以我会建议使用 f + = 1.0f

++/-- is defined as "increment/decrement by 1". Therefore this is applicable to floating point values. However, personally i think, that this can be confusing to someone who isn't aware of this definition (or only applies it to integers), so i would recommend using f += 1.0f.

这篇关于在浮点坏样式上使用increment(operator ++)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆