typecasting

Hello everybody,

I have an array that I calculated the sum of 10 integer elements in an array, and now I am finding the average, but it has to be of float type.
Before I found this website: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fkeyword_static_cast.htm
I tried implementing typecasting by doing this:
1
2
	float avg = static_cast<float>(Sum(store)/10);
	return avg;

but instead of the answer I was looking for, say, 2.4, it returned 2.
Could someone explain why does putting the parentheses only around Sum(store) work but around the whole expression doesn't?
If you put it around the whole expression, you are doing integer division *first*, which means you get an integer answer. Casting the integer to a float afterwards doesn't help.
An alternative method is to divide by 10.0 which makes your division become a double. To get a float, divide by 10.0F. This signifies that the type is float and will return a float as so.

To keep using the static_cast, you would want something similar to:
float avg = (static_cast<float>(Sum(store))/10);

This will force the return of Sum(store) to be a float and I believe a float divided by an integer should give you a float in return.

The division is at times a pain in the butt, but just remember, you get the highest precision as the highest precision value you put into it.
int/int will return int
int/float will return float
int/double will return double

Atleast that's how I've always looked at it. I could vary well be wrong.
Topic archived. No new replies allowed.