开发者

Why go through the trouble of static_cast-ing a number to a double?

Ran across this in code I'm working 开发者_StackOverflow社区through:

double part2 = static_cast<double>(2) * somthing1
  * ( static_cast<double>(1) + something2 )
  + ( static_cast<double>(1) / static_cast<double>(2) ) * something3
  + ( static_cast<double>(1) / static_cast<double>(2) ) * pow ( something4, 3 );

(The somethings are doubles.)

I suspect that there's a really good reason for going through the trouble of doing

static_cast<double>(1)

and the like, but it seems like I could get by with a lot less typing.

What am I not understanding?

Thanks in advance.


Many of these static_casts are unnecessary, because of automatic numeric promotion. The ones that are extremely necessary are the ones used on constructing the number 1/2, although in this case there's no obvious reason not to just say 0.5 instead. In any case a compiler that's paying attention will remove all of these and replace them with compile-time constants.


I agree with the previous answer that 2.0 would be much better here.

However, I found another red flag in the code, namely pow(something, 3). The pow function is designed to take two arbitrary values, x and y and return x^y. As this function must handle arbitrary values, it will do an approximation. However, this 1) is complex to calculate and 2) sometimes miss the mark. In this case, you would be much better of simply using something4 * something4 * something4.


This is equivalent to the much more readable

double part2 = 2 * somthing1 * (1 + something2)
  + 0.5 * something3 + 0.5 * something4 * something4 * something4

since integers are promoted to doubles each time an arithmetic operation has one double operand. The 0.5 double litteral is enough to promote everything to double.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜