Division: using floats and integers

Assuming that a variable x and y are integers, while variable a is a float. Identify and explain the problem with the following code. Re-write the code with this problem corrected.

a = x/y;

My analyses:
If we dividing 5/2. Would it return 2.5 or only 2. Since they are int.

Hope anyone can explain better.
Thanks
Last edited on
It would return 2.0 instead of 2.5. since we are dividing 2 int.
to have a right result, it should be all float.

is that right, should I add anything else.

This is an exam question!!
Thanks for looking!!
if x and y are integers, x/y is a integer (2). When float a=2, then a is 2.0. So if you really want the answer to be 2.5, you need to change at least one of the numbers to a float. Here are a few options:

1. a=1.0*x/y

2. a=float(x)/y // C style casting

3 a=static_cast<float>(x)/static_cast<float>(y) //this is what I would recommend, assuming that you are familiar with casting. There are some tutorials on this site.
Thanks, I forgot about type casting!!
Topic archived. No new replies allowed.