home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Lion Share
/
lionsharecd.iso
/
utils_mz
/
v10n14.zip
/
TRYVECS.CPP
< prev
next >
Wrap
C/C++ Source or Header
|
1991-04-27
|
3KB
|
97 lines
// TRYVECS.CPP - Try Overloaded + Operator for Vector Data Type
// Compile with Borland C++ 2.0
// Copyright (C) 1991 Ziff Davis Communications
// PC Magazine * Ray Duncan April 1991
// Note: all directions for input and output are in degrees,
// but calculations are carried out internally in radians.
#include <math.h>
#include <iostream.h>
const double pi = 3.141592654; // constant Pi
// local function prototypes
double deg2rad(double); // convert degrees to radians
double rad2deg(double); // convert radians to degrees
struct VECTOR { // vector data type
double magnitude;
double direction; } ;
VECTOR operator + (VECTOR A, VECTOR B); // vector operator prototype
main()
{
VECTOR A, B, C; // instantiate 3 vectors
cout << "\nAdd two vectors.";
cout << "\nNote: directions are entered in degrees!\n\n";
cout << "Enter Vector A magnitude: "; // prompt for Vector A
cin >> A.magnitude;
cout << "Enter Vector A direction: ";
cin >> A.direction;
cout << "Enter Vector B magnitude: "; // prompt for Vector B
cin >> B.magnitude;
cout << "Enter Vector B direction: ";
cin >> B.direction;
A.direction = deg2rad(A.direction); // convert degrees to radians
B.direction = deg2rad(B.direction);
C = A + B; // add the vectors
C.direction = rad2deg(C.direction); // radians to degrees
cout << "\nVector result: " // display the result
<< " magnitude = " << C.magnitude
<< " direction = " << C.direction << "\n" ;
}
VECTOR operator + (VECTOR A, VECTOR B) // vector addition operator
{
VECTOR temp; // scratch storage
double angle; // scratch storage
angle = B.direction - A.direction; // find angle between vectors
if (angle == pi) // special handling to avoid
{ // overflow for angle=180
temp.magnitude = fabs(A.magnitude - B.magnitude);
temp.direction = A.magnitude>B.magnitude ? A.direction : B.direction;
return temp;
}
if ((A.magnitude == 0) && (B.magnitude == 0))
{
temp.magnitude = 0; // special handling to avoid
temp.direction = 0; // divide by zero if both
return temp; // magnitudes = 0
}
temp.magnitude = sqrt( // find magnitude of result
(A.magnitude * A.magnitude) +
(B.magnitude * B.magnitude) +
(2 * A.magnitude * B.magnitude * cos(angle)));
temp.direction = A.direction + // find direction of result
asin(((B.magnitude * sin(angle))/temp.magnitude));
return temp; // return resultant vector
}
double deg2rad(double degrees) // convert degrees to radians
{
return ((degrees * 2 * pi)/360);
}
double rad2deg(double radians) // convert radians to degrees
{
return ((radians * 360)/(2 * pi));
}