/* Unit tests for Vector class */ #include "stdstuff.h" #include "Vector.h" using namespace std; #define __VERSION_i #if defined __VERSION_x double getX(const Vector& v) { return v.x; } double getY(const Vector& v) { return v.y; } double getZ(const Vector& v) { return v.z; } #elif defined __VERSION_i double getX(const Vector& v) { return v.i; } double getY(const Vector& v) { return v.j; } double getZ(const Vector& v) { return v.k; } #else double getX(const Vector& v) { return v.a; } double getY(const Vector& v) { return v.b; } double getZ(const Vector& v) { return v.c; } #endif int read() { Vector r; cout << "Test read() (enter 3 -5 6): "; r.read (cin); return (getX(r) == 3 && getY(r) == -5 && getZ(r) == 6); } int write() { Vector r(-2, 16, -4); cout << "Test write(): "; r.write(cout); cout << endl; return 0; } int addition() { Vector f1(1,-4,3),f2(1,2,8),t; t.add (f1); // (1, -4, 3) t.add (f2); // (2, -2, 11) return getX(t) == 2 && getY(t) == -2 && getZ(t) == 11; } int crossProduct() { Vector f1(3,-65,-99),f2(12,23,33),r1; r1 = f1.cross(f2); // (132, -1287, 849) return getX(r1) == 132 && getY(r1) == -1287 && getZ(r1) == 849; } int dotProduct() { Vector f1(32,-4,-23),f2(-5,7,3); double r1; r1 = f1.dot(f2); // -257 return ((r1 == -257)); } int magnitude() { Vector v(23,43,2); // Note: I cast to int because there might be precision differences if the student did // not use the pow() function but did x*x return (floor(v.magnitude()) == floor((sqrt(pow(23,2) + pow(-43,2) + pow(3,2))))); } int unitize() { Vector v(34,65,23); float m = sqrt(pow(34,2) + pow(65,2) + pow(23,2)); v.unitize(); return (sqrt(pow(getX(v),2) + pow(getY(v),2) + pow(getZ(v),2)) == 1); } int unitizeException() { Vector v(0,0,0); try { v.unitize(); } catch (domain_error &e) { return 1; } catch(...) { return 0; } return 0; } void printTest(char* testname, int score, int possible, int& totalScore) { if (possible == 0) cout << "(+1 if similar to '- 2i + 16j - 4k') " << testname << endl << endl; else cout << "(" << score << "/" << possible << ") " << testname << endl << endl; totalScore += score; } int main() { int total = 0; const int overallTotal = 8; printTest("Vector reading.", read(), 1, total); printTest("Vector printing.", write(), 0, total); printTest("Vector addition.",addition(),1,total); printTest("Dot product.",dotProduct(),1,total); printTest("Cross product.",crossProduct(),1,total); printTest("Magnitude of vector.", magnitude(),1,total); printTest("Vector normalize (unitize).", unitize(),1,total); printTest("'domain_error' exception thrown for attempt to unitize zero vector.", unitizeException(),1,total); cout << "---------------------------------------------" << endl; cout << "TOTAL: " << total << "/" << overallTotal << " (+1? See above.)" << endl; pause(); }