#include <iostream>
using namespace std ;
int main ()
{
int x,y ;
x= 7 , y=3 ;
cout<<float(x) /y << endl ;
}
What is the difference between float(x)/y
and x/float(y)
?
#include <iostream>
using namespace std ;
int main ()
{
int x,y ;
x= 7 , y=3 ;
cout<<float(x) /y << endl ;
}
What is the difference between float(x)/y
and x/float(y)
?
There is no practical difference in your question.
The result of dividing two integers is an int
(this is called integer division and what you get if you omit the float
conversion entirely); if you then cast to a float
you still have the int
result, albeit as a float
. The result of dividing a float
and an int
is a float
; so you aren't promoting the int
result to a float
.
There was a similar question involving uint8_t
and bool
s in an arithmetic expression.
The answers to that question apply here also, with the following additional information relevant to float
s.
5 Expressions
9 Many binary operators that expect operands of arithmetic or enumera- tion type cause conversions ...
--Otherwise, if either operand is float, the other shall be converted to float.
Both the operands are converted to float
before the division and the resultant is of type float
.
Very little. With float(x)/y
the value x
will first be converted to float
and then to double
while y
will be converted directly to double
. With x/float(y)
, x
will be converted directly to double while y
will be converted to float
and then double
. In either case, the division will be carried out as double
and the double
result will be printed.
So for your example, there is no difference, but if x
or y
was larger (greater than 224), then the value would be rounded slightly to fit in a float
if it was first converted to float
. This would then give a (very) slightly different result.