Variable Conversion

I have an assignment requiring me to demonstrate widening (converting a smaller variable type like int to a larger one like float) and narrowing (the opposite). I've looked up type casting, but it isn't working for this example.

The code I tried is:

1
2
3
4
5
6
{
	int x = 1/3;
	float y = x;
	cout << x << endl;
	cout << y << endl;
}


If I understand this correctly, y is the lValue and x is called the rValue (based on their placements in y = x, with the lValue needing to be the largest), and from what I've read, this should work. X comes out as 0, as it should, but float should be 0.333etc, but it just comes out as 0, too.
By the rules of integer division, the result of 1/3 is 0.
Therefore, a 0 is stored into x.

When you assign the value of x to y, you assign 0 to y, and thus the value of y becomes 0.


Note: a float is probably never exactly 0.333etc, because float stores only discrete values and therefore the float will contain nearest representable discrete value that the implementation of float allows. Floating point math is not exactly intuitive.
Thanks Keskiverto. I do understand that part. What I'm trying to show in the output when I run the program is that x will output as 0, while y will output as 0.333etc. The math isn't what's important here, and it doesn't have to be an int to float conversion. I tried something similar with short to long, but had the same problem, y always outputs to the same value as x instead of converting. I'm hoping someone will be able to help me convert one variable output into another.

x == 0, so y = x results in y being the same as the value held by x i.e. 0
I tried something similar with short to long, but

If you have 4cl of whisky in a glass and pour it into a large bucket, it is still 4cl, isn't it?

On the other hand, trying to pour a full bottle into a small glass does create a flood (and a loss of quality material).
Topic archived. No new replies allowed.