Data types

I am writing something which could:
1) take a point
2) find distance to origin
3) compare to one before and submit closest one
4) if within 0.01 of origin it terminates

It does compile but it does not work? it outputs odd numvers e.g for (10,9) it would submit something like ''the closest point to the origin so far: 8.00831e-307 8.00991e-307'' what is wrong?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
   #include <iostream>
#include <cmath>


struct point{
   double x;
   double y;
};

double pdistance (point p1, point p2);


int main(){

   point pa, pb, o;
   double d1, d2;
   o.x = 0;
   o.y = 0;

   d2=0;
   // intialising d2 to to make the loop correct

   do{
     std::cout<< " enter the co-ordiantes of a point" << std::endl;
     std::cin >> pa.x >> pa.y ;


    d1 = pdistance(pa, o);

     if(d1<d2){
       std::cout << " the closest point to the origin so far: " << pa.x << " " << pa.y << std::endl;
     }
     else{
       std::cout << " the closest point to the origin so far: " << pb.x << " " << pb.y << std::endl;
     }

     d2=d1;
     //storing the value of d1 into d2 here so it can be compared once another point is put in


 }while(d1||d2 > 0.01);

}


double pdistance(point p1, point p2){
   return std::sqrt(
     std::pow((p1.x-p2.x), 2)+
     std::pow((p1.y-p2.y), 2)
   );
}
Last edited on
You haven't set pb anywhere yet you are almost certain to try to output it on line 34.

You set the minimum distance d2 to 0 initially (line 20). So line 30 cannot be true on the first pass.

And on subsequent passes, line 37 ensures that d2 will always be the previous value, not the smallest one.

And line 41
while(d1||d2 > 0.01);
doesn't do what you think it does.



thank you for your response. What does line 41 mean when put this way?

When a number is used where a boolean value is expected zero will be treated as false and everything else as true.

It's as if you had written:
 
while(d1 != 0.0 || d2 > 0.01);
Last edited on
Topic archived. No new replies allowed.