Casting in mixed type computing in C?

If I define these variables:

double x0, xn, h;
int n;

and I have this math expression:

h = (xn - x0)/n;

Do I need to do n in double before doing division for maximum precision, as in

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

I wrote a program to check above, but both expressions give the same answers. I understand that C will stimulate an integer to a double type, since the variables xn and x0 are of type double, but, oddly enough, in the book, the second cast expression was emphasized.

My question will be if I think correctly.

Thank you so much...

+3
source share
4 answers

, , (, , , 0 == x x == 0). , .

+3

, , double. n double. , xn x0 int, .

+2

. , , . . : double(end_time-start_time)/CLOCKS_PER_SEC; , ( ) , .

+1

In C, the precision of any expression is the same as the high precision constant involved in the expression.

Explicit roles are useful:

  • As a precaution .

Tomorrow you can edit the variables in the expression to use ints. Cast will still return the correct value

  • As a guide .

Someone else referencing / modfiying ur code will easily understand that U is using double .

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

+1
source

Source: https://habr.com/ru/post/1741610/


All Articles