"Eurig Jones" <eu***@one47.com> wrote in message news:bo*******************@news.demon.co.uk...
int one = 1;
int number = 43;
These are two integers.
double result = one / number;
Ignore the stuff to the left of the = sign for now. The expression
one/number
has value zero, becaue integer divide throws away the fractional values.
1/43 is 0, 42/43 is 0, 43/43 is 1.
So in effect you have:
double result = 0;
The int zero is converted to double and initializers result. You have a double value of
zero.
double result2 = static_cast<double>(one / number);
The same thing happens here. The sub expression one/number is still 0.
double result2 = static_cast<double>(0);
The static cast converts it to double, but it's still zero.
If you want to do a floating point divide, you must convert at least one of the
operands to a floating point type (if you convert only one, the compiler will
automatically convert the other to match).
double result = static_cast<double>(one) / number;
for example. This convets the 1 to a double. The compiler now does the divide,
converting number to double to match (there are a list of "usual artithmatic conversions"
that gets applied to operators when the types of the operands don't match, generally
the least precise of the two is converted to the more precise).
The result of this expression is the 1.0/43 or about .023...