Reputation: 94
I do not understand the underlying reason the output is a double between the following examples. In terms of:
Why does a int divided by a double result in a double?
#include <stdio.h>
int main(int agrc, char **argv)
{
double d;
int a=5,b=2;
d = (double)a/b;
printf("d= %G\n",d); // outputs 2.5
d = a/(double)b;
printf("d= %G\n",d); // outputs 2.5
}
Upvotes: 2
Views: 87
Reputation: 225387
From the C standard, section 6.3.1.8: Usual arithmetic conversions:
First, if the corresponding real type of either operand is long double, the other operand is converted, without change of type domain, to a type whose corresponding real type is long double.
Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is double.
Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float.
Otherwise, the integer promotions are performed on both operands.
So if one operand to an arithmetic operator is int
and the other is double
, the standard states that the resulting expression has type double
.
Upvotes: 4
Reputation: 23236
For additional context of @dbush 's excellent answer, it is important to note that the standard specifies that for all arithmetic type conversions containing differing types, that conversion is from the smaller of two types to the largest:
Summarized from C11 - 6.3.1.8 Usual arithmetic conversions:
1st: if real type of either operand is long double, the other is converted to long double
2nd: Otherwise if real type of either operand is double, the other is converted to double
3rd: Otherwise if real type of either operand is float, the other is converted to float
And it goes on to specify how integer promotions are made in similar fashion...
Upvotes: 1
Reputation: 7352
Due to necessities in the evaluation, if one of the operands of a division is a double data type, the other is automatically promoted to that for means of calculation. In your example this happens because the operator precedence for an explicit cast is higher then for a divison.
If you want to only cast the result of the division, you can do:
d = (double)(a/b);
To ensure the integer division is performed first, and the explicit cast to double is performed second.
Upvotes: 1
Reputation: 126
The cast has precedence over the division, and an operation between a double
and an int
will produce a double
Upvotes: 1