0

Here is my code for the problem : Check If It Is a Straight Line

 bool checkStraightLine(vector<vector<int>>& a) {
        double m = (((double)a[1][1]-a[0][1])/(a[1][0]-a[0][0]));

        for(int i=1;i<a.size()-1;i++)
        {

                double slope=(((double)a[i][1]-a[i+1][1])/(a[i][0]-a[i+1][0]));

                if( m!=slope)
                    return false;
        }
        return true;
    }

My doubt is why does my code produce an error when I replace :

double m = (((double)a[1][1]-a[0][1])/(a[1][0]-a[0][0]));

with

double m = (double)((a[1][1]-a[0][1])/(a[1][0]-a[0][0]));

and

double slope=(((double)a[i][1]-a[i+1][1])/(a[i][0]-a[i+1][0]));

with

double slope=(double)((a[i][1]-a[i+1][1])/(a[i][0]-a[i+1][0]));
Harini Sj
  • 173
  • 1
  • 2
  • 11

1 Answers1

3

Given:

int a = 1 , b = 2;

this line of code:

double d = (double)(a/b);  // d is 0.

is not the same as:

double d = ((double)a/b);  // d is 0.5

In the first case, you are doing an integer division before converting the result.

In the second case, you are converting the numerator to a double, and then dividing, which does a floating point division.

In your case, the error might be coming about because the code expects a non-zero slope, but the integer division gives you a zero.

Note that this comparison:

 if( m!=slope)

is fundamentally flawed. You should never compare floating point numbers for equality. Use a threshold for the comparison instead.

cigien
  • 57,834
  • 11
  • 73
  • 112