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:

  1. 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.

  2. you returning int point::set_lenght cast double - cast not rounding, it's truncating. change return double.

btw, distance between points (4,1) , (8,2) not 3. it's 4.12310563.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -