Question

I have written a program using Xlib headers in c++ This is a part of it.

XPoint m[5];

m[0].x = 0; m[0].y = 400;
m[1].x = 150; m[1].y = 250;
m[2].x = 250; m[2].y = 300;
m[3].x = 300; m[3].y = 200;
m[4].x = 450; m[4].y = 400;

float slope=(m[2].y-m[1].y)/(m[2].x-m[1].x); cout<<slope<<endl; 

slope should be 0.5 but it gives 0. Can you please explain why and what's the correct way?? Is it because of the XPoint?? Help is greatly appreciated.

Was it helpful?

Solution

It seems the members x and y are of an integral type, so the division is done on integers, which simply truncates the fractional part of the result. In other words, 50 / 100, which is 0.5, gets truncated to the 0 you see in your output.

In order to avoid that, you must cast one of the operands to a floating point value, like this:

float slope = static_cast<float>(m[2].y-m[1].y)/(m[2].x-m[1].x);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top