classes, one particular problem

program checks for distance between two points. one function checks for if the two points are the same and returns a 1. program runs, however it always displays "two points are the same distance". It is not doing "else". I dunno whats wrong with it.

# include <iostream>
# include <cmath>
using namespace std;

class Point
{
private:
double x, y, z;
public:
void prompt_user();
void display();
Point();
double dis(Point);
double equal(Point);




};

//**************************************************************

void Point::prompt_user()
{ cout << "Enter three coordinates for a point: " << endl;
cin >> x >> y >> z;
}
void Point::display()
{ cout << x << " " << y << " " << z << endl;
}

Point::Point()
{ x=0;
y=0;
z=0;
}

double Point::equal(Point P2)
{ double test;
test = ((P2.x - x)+(P2.y - y)+(P2.z-z));
if(test == 0)
return 1;
else
return 0;
}


double Point::dis(Point P2)
{ return(sqrt(pow(P2.x - x,2.0)+ pow(P2.y - y,2.0)+ pow(P2.z - z,2.0)));

}



//****************************************************************

int main()
{ Point A, B;
double distance,check ;

cout << "This program calculates the distance between two points." << endl;

A.prompt_user();
B.prompt_user();



cout <<"Point 1: ";
A.display();

cout <<"Point 2: ";
B.display();


check = A.equal(B);
distance = A.dis(B);




if(check = 1)
cout << "Distance is the same between both points." << endl;

else

cout << "The distance between the two points is: " << distance << endl;





system("pause");
return 0;
}
Turn this -> if(check = 1) into this -> if(check == 1) and it should be fine.

You see, = is the assignment operator. The operator for equality testing is ==.

The way you do it, the value 1 is stored in check and then check is tested for being true (and of course it is true, because you just stored the value 1 in it)

More info on operators -> http://cplusplus.com/doc/tutorial/operators/
Last edited on
Topic archived. No new replies allowed.