0

I have written the code which will print the slope from the coordinates of a line and then print it. but when I give input, my code is terminating. what is the problem?

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int x1,y1,x2,y2,m;

    cin>>x1>>y1>>x2>>y2;

    m=(y1-y2)/(x1-x2);

    cout<<m;
}
imtinan
  • 141
  • 6

4 Answers4

4

Problem is probably here m=(y1-y2)/(x1-x2);. When x1==x2 you have division by zero, please add some checks.

ufoq
  • 103
  • 2
  • 6
1

Consider adding more corner tests, also note when x1 is equal to x2 you will face division by zero error, so you should modify your program with if statement to check that they are not equal.

so you should add this to your code:

if(x1==x2){
  cout<<"Error division by zero"<<endl;
  return 1;
}
NAND
  • 645
  • 7
  • 21
-1

The program works fine:

g++ x.cpp
./a.out
1 2 3 4 5
1⏎
Ludwig Schulze
  • 1,775
  • 13
  • 31
-1

I tested your code using c++ compiler online and it worked.

You may have a compiler error or something else.

omri klein
  • 138
  • 6
  • The program does *not* work for all input. It's trivial to provide input that causes it to divide by zero. That's not what I would call a "working" program. – Jesper Juhl May 25 '20 at 19:43
  • Not handling extreme cases does not mean the program is not working. The question didn't tell about the input that makes the program terminate. I also said that the error can be something else (for example, input), but it generally works. – omri klein May 25 '20 at 19:54
  • Passing two identical numbers to something that subtracts them and then does a division is hardly an *extreme* case. – Jesper Juhl May 25 '20 at 19:55