Reputation: 2088
I am learning C. I was wondering why you get a float, even if one of your variables is an int.
float x = 5.0;
int y = 2;
float result = x / y;
My guess would be that result would be 2.00000. But it does return a float (2.500000)
I think it would be 2.000000 because if you divide 2 ints that is the result. And I would think that if you use an int and a float it would pick the least precise value.
Upvotes: 0
Views: 10368
Reputation: 486
The result of the code is a float and therefore it will produce a float. When you devide an int by anf int it will return 2.5 but the result being an int truncates the result to be 2
Upvotes: 0
Reputation: 126937
And I would think that if you use an int and a float it would pick the least precise value.
That's exactly the opposite; the general rule is that before performing any arithmetic operation both operands are promoted to the "most powerful" type of the two involved in the operation.
The "most powerful" type is determined according to the rules that the standard calls "Usual arithmetic conversions" (C99, §6.3.1.8), which essentially say that
long double
> double
> float
> all integral types; if an expression involves only integral types, some other rules kick in that are a bit more lengthy to describe (at §6.3.1.1).
Now, in your case you have an int
and a float
, the "best" type is float
and thus the int
is promoted to float
before performing the division.
Upvotes: 1
Reputation: 16825
Because of C's Usual arithmetic conversions
.
Quoting the ANSI C standard § 3.2.1.5 Usual arithmetic conversions:
Many binary operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions: First, if either operand has type long double, the other operand is converted to long double . [...] Otherwise, if either operand has type float, the other operand is converted to float.
Emphasis mine.
Upvotes: 4
Reputation: 90
First of all, result
is a float, so it can hold decimal values.
Secondly, one of the operands x
, and y
is a float, so the returned value is a float. This holds for addition, multiplication and subtraction also.
Upvotes: 0
Reputation: 44906
If one of the operands in you division is a float
and the other one is a whole number (int
, long
, etc), your result's gonna be floating-point.
This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.
Upvotes: 0
Reputation: 11377
The operator /
only performs integer division if both operands are integers.
Upvotes: 2