Hi everybody,
I am working on a class that takes the coordinates of two points and calculates the slope and distance between them. However, I would like to have the values to be taken as user input, rather than always having to go back and change them. What would be the most efficient way to do this? I tried the cin operator and for some reason it gives me non-sense. Thanks. Code is below.
#include<iostream>
#include<cmath>
usingnamespace std;
class Point {
double x1, y1, x2, y2;
public:
void set_values (double, double, double, double);
double slope(){return (y2-y1)/(x2-x1);}
double distance() {return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));}
};
void Point::set_values (double nx1, double ny1, double nx2, double ny2) {
x1 = nx1;
y1 = ny1;
x2 = nx2;
y2 = ny2;
}
int main() {
Point point;
cout << "Enter the x and y coordinates of the two points: " << endl;
point.set_values(1.0, 1.0, 4.0, 5.0);
cout << "The slope of the line going through the points is " << point.slope() << endl;
cout << "The distance between the two points is " << point.distance() << endl;
return 0;
}
#include <iostream>
#include <cmath>
usingnamespace std;
class Point {
double x, y;
public:
friend std::istream& operator >> (std::istream& is, Point& p)
{
is >> p.x >> p.y;
return is;
}
friend std::ostream& operator << (std::ostream& os, const Point& p)
{
os << '(' << p.x << ',' << p.y << ')';
return os;
}
};
// Line defined by two Points
class Line {
Point a, b;
// etc.
// etc.
};
int main()
{
Point point;
cout << "Enter the x and y coordinates of the point: " << endl;
cin >> point;
cout << "The point is: " << point << endl;
}