Question

I have a few questions as to what the results of these operations are.

Firstly, if I have two integers and divide them and save the result in a double. Will there be any rounding issues such that 1/2 will equal .5 and not 1.

double ratio = int1/int2;

Second, if I now have this ratio and multiply it by a UWORD will there be any problems?

UWORD word1 = 4098;
UWORD word2 = ratio * word1; 

By the way, I do get compiler warning when I do do these

 narrowing or signed-to-unsigned type conversion found: double to unsigned short
Was it helpful?

Solution

You need to cast int1 to a double so the compiler know to use floating point calculations (instead of integer ones):

double ratio = ((double) int1) / int2;

To store the floating point calcualtion of ration * word1 in the UWORD you need to cast it again (to prevent warnings):

UWORD word2 = (UWORD) (ratio * word1);

Note: this will chop off the decimals, if you need proper rounding try the round() function, available from math.h. (Again, with proper casting!)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top