K
kwikius
Jim said:Well, your program would work with a little modification, but what about now
you want to know the average of the distances, etc? You are not storing the
points.
Two ways, like I said. A dynamic array, or a std::vector. I believe in
your case a std::vector would be prefered.
Another alternative is a recursive function. (mag_n below). In this
case the function call stack is used to store intermediate reults:
Also makes gratuitous use of the infamous GOTO
regards
Andy Little
//---------------------------------
#include <iostream>
#include <cmath>
#include <string>
// a 2D vector type
struct vect{
double x,y;
vect():x(0),y(0){}
vect (double const & x_in, double const & y_in)
:x(x_in),y(y_in){}
};
inline
vect operator -(vect const & lhs, vect const & rhs)
{
return vect(lhs.x-rhs.x,lhs.y - rhs.y);
}
std::istream & operator >>(std::istream & in, vect & pt)
{
in >> pt.x >> pt.y;
return in;
}
std:stream & operator <<(std:stream & out, vect const & pt)
{
out <<'(' << pt.x << ','<< pt.y << ')';
return out;
}
inline
double magnitude(vect const & v)
{
return std::sqrt(v.x * v.x + v.y * v.y);
}
typedef vect point;
double mag_n( point const & p_in, int current_point, int const
num_points)
{
int next_point = current_point + 1;
std::cout << "Enter point number " << next_point << " : ";
point p;
std::cin >> p;
double result = magnitude( p - p_in);
if( next_point < num_points) {
result += mag_n(p,next_point, num_points);
}
return result;
}
int main()
{
// the infamous goto...
start:
std::cout << "Enter num points to input : ";
int num_points = 0;
std::cin >> num_points; std::cout << '\n';
if ((num_points <2) || (num_points > 10)){
std::cout << "Error: must be 2 <= num points <=10\n";
goto start;
}
std::cout << "Enter first pointsyntax x y) : ";
point p;
std::cin >> p;
double result = mag_n(p,1, num_points) ;
std::cout << "path length = " << result <<'\n';
std::cout << "Do another set of points? (y/n) : ";
std::string str;
std::cin >> str;
if ( str.substr(0,1) == "y"){
goto start;
}
}