Reputation: 9
I wrote a code like this :
#include<iostream>
using namespace std;
int main()
{
cout<<static_cast<float>(5/9)*9;
cout<<static_cast<float>(5)/9*9;
return 0;
}
Expected output :55
Original output :05
Why the first static cast statement turned to 0 ?
Upvotes: 1
Views: 155
Reputation: 311068
In this sub-expression
(5/9)
of this statement
cout<<static_cast<float>(5/9)*9;
there is used the integer arithmetic. The result of the sub-expression is 0. This result is converted to the type float.
static_cast<float>( 0 )
That is the casting is applied to the primary sub-expression in parentheses after its evaluation.
In the second statement
cout<<static_cast<float>(5)/9*9;
that is in fact equivalent to
cout<< 5.0f/9*9;
in the sub-expression
static_cast<float>(5)/9
or that is the same
5.0f / 9
there is used the arithmetic with floating numbers and the result is not equal to 0.
Upvotes: 5