c++ - I'm having trouble with formula,program runs fine but the answer seems to be wrong -
the following program should calculate distance between 2 points:
header.h
class point{ private: double x, y, length; public: point(); point(double a, double b); int set_length(point,point); };
header.cpp
#include<iostream> #include"header.h" #include<math.h> using namespace std; point::point() :x(0), y(0) { } point::point(double a, double b){ x = a; y = b; } int point::set_length(point p1, point p2){ length = sqrt(((p2.x - p1.x)*(p2.x - p1.x)) + ((p2.y - p1.y)*(p2.y -p1.y))); return length; }
main.cpp
#include<iostream> #include"header.h" using namespace std; int main(){ point p1(4, 1); point p2(8, 2); point length; cout << length.set_length(p1, p2) << endl; }
the answer should 3
not.
could me implement distance formula?
you didn't provide actual output get, but, here possible causes of errors:
you're on unix-like system , didn't give
-lm
parameter linker, math library not linked in, , weird behavior. can similar problems if don't link math library on other systems. so, sure link math library.you returning
int
point::set_lenght
castdouble
- cast not rounding, it's truncating. change returndouble
.
btw, distance between points (4,1) , (8,2) not 3. it's 4.12310563.
Comments
Post a Comment