Dividing integers.

I have some code that goes through some steps (Very specific).Essentially it comes down to assigning x to be x/y. X and Y are both integers so when they divide, they don't always equal an integer (5/2=2.5). I have tried using the following to get around it.
1
2
3
4
5
6
7
8
9
int x=5;
int y=2;
{
double x = x;
double y = y;
double z = x/y;
x=z;
cout << x;
}

The answer came out to be 5.25 every time, even when x and y had different values.

1
2
3
4
5
6
7
int x = 5;
int y = 2;
{
double z = x/y;
double x=z;
cout << x;
}

The 5/2 was always just 2.
I have tested what z became and it is becoming 2 even though 5/2 = 2.5.
I assume this is because x and y are integers.
Last edited on
Try something like:

1
2
3
4
5
int x = 5;
int y = 2;
double z = static_cast<double>(x) / y;

cout << "x = " << x << "  y = " << y << " x / y = " << z << endl;


To get a floating point result at least one of the numbers needs to be a floating point type. So in this case casting one or both of the int values to a double will produce a double result.


Topic archived. No new replies allowed.