Reputation: 9
I was testing out type casting in C++ today after reviewing a past quiz and can't for the life of me figure out why my 'x' value changes from 9 to 4.5000 in the following code.
int main(){
int x = 9, y = 2;
float z;
z = (float)x/(float)y;
printf("\n%f", z);
printf("\n%f", x);
printf("\n%d", x);
}
Outputs
4.5000
4.5000
9
I'd appreciate any help!
Upvotes: 0
Views: 154
Reputation: 1148
It is not cutting your X in half. look at the code below it still prints 4.5
#include <stdio.h>
int main(){
int x = 9, y = 2;
float z;
z = (float)x/(float)y;
x = 15;
printf("\n%f", z);
printf("\n%f", x);
printf("\n%d", x);
}
this prints:
4.500000
4.500000
15
May be it has to do internally with how floats and ints are stored on stack. Its fishy because its the first float value that gets stored. If I change the code to this:
#include <stdio.h>
using namespace std;
int main(){
int x = 11, y = 2;
float z;
z = (float)x/(float)y;
x = 15;
printf("\n%f", z);
printf("\n%f", x);
printf("\n%d", x);
}
the output is
5.500000
5.500000
15
If you dont print the variable z
, then the output becomes
0.000000
15
So may be it has to do with the order of printing.
Upvotes: 0
Reputation: 198476
In printf("\n%f", x)
with an int x
, you are not casting x
to float
- you're assuming it's a float. It's like handing a firefighter a stick of butter and telling him it's a fire extinguisher - won't work right.
In order to cast, you either have to assign the value to a cast-compatible variable:
float floatX = x;
printf("\n%f", floatX);
or use the cast operator:
printf("\n%f", (float)x);
Upvotes: 6
Reputation: 37192
The printf
function is expecting a float
to be on the stack (because of %f
) and you've only provided an int
.
You need to cast x
to a float
in that case:
printf("\n%f", (float)x);
Upvotes: 8