开发者

Casting in mixed type calculations in C?

If I define these variables:

double x0, xn, h;
int n;

and I have this mathematical expression:

h = (xn - x0)/n;

Is it necessary that I cast n into double prior doing the division for maximum accuracy like in

h = (xn - x0)/ (double) n;

I wrote a program to check the above but both expressions give the same answers. I understand that C will promote the integer to double type as variables xn and x0 are of type double but strangely enough in a book, the seco开发者_运维百科nd expression with casting was emphasized.

My question would be if I'm thinking right.

Thanks a lot...


Your understanding is correct, and the book you read is either mistaken or being over-cautious (like people who claim that you should always test 0 == x instead of x == 0). The expression without the cast should always give precisely the same result as the expression with the cast.


No, this conversion is unnecessary because the numerator is a double. This promotes n to a double as well. The book probably mentions the explicit cast as a good habit, because if xn and x0 were ints then the expression would only use integer division.


It's unnecessary in this situation. It's typically needed in situations where you want a result that's different in type from the operands. A typical one is when doing timing. You often end up with code like: double(end_time-start_time)/CLOCKS_PER_SEC; In this case, the cast really is needed, because all the inputs are (typically) integer types, but you want a floating point result.


In C, the precision of any expression is the same as the highest precision constant/variable involved in the expression.

Explicit Casts are useful:

  • As a precaution.

Tomorrow you may edit the variables in the expression to use ints. A cast would still return the proper value

  • As a guide.

Someone else refering/modfiying ur code will easily understand that U are using a double.

i.e. "Let Ur code be its own comment !!"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜