"Johs" <sd*@sdf.comwrote in message news:en**********@news.net.uni-c.dk...
>I have:
int a = 1;
int b = 2;
double c = a/b;
Is it somehow possible to divide these two integers and get the result as
a double 0.5? Or do they both have to be declared as doubles?
If you trust the compiler:
double c = (double)a / b;
If you don't trust the compiler and have paranoid personality disorder:
double c = (double)((double)((double)((double)((double)a / (double)b))));
/* "double" MUST occur 7 times. */
Seriously, the first example works because the compiler is required to
convert and/or promote operands according to certain rules before doing the
division:
<BEGIN>
First, if either operand has type long double , the other operand is
converted to long double.
Otherwise, if either operand has type double , the other operand is
converted to double.
Otherwise, if either operand has type float , the other operand is converted
to type float.
Otherwise, the integral promotions are first applied to both operands and
then the following rules are applied.
If either operand has type unsigned long int, the other operand is converted
to unsigned long int.
Otherwise, if one operand has type long int and the other has type unsigned
int, if a long int can represent all values of an unsigned int, the operand
of type unsigned int is converted to long int; if a long int cannot
represent all the values of an unsigned int, both operands are converted to
unssigned long int
Otherwise, if either operand has type long int, the other operand is
converted to long int.
Otherwise, if either operand has type unsigned int, the other operand is
converted to unsigned int.
Otherwise, both operands have type int.
<END>
That is why it isn't necessary to cast b.
The second example has the advantage that the word "double" occurs 7 times.
If you program in a team environment, you'll find that examples like this
can hang around in the code for years. It won't be changed because your
colleagues (a)are afraid of offending you, (b)know that the code is
superfluous but are afraid of breaking something, especially because the
comment seems to imply it is necessary, (c)aren't competent enough to
understand that the code is superfluous.
Dave.