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.
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.