// // //Original author: Gordon Griesel //Date: November 2023 //Purpose: 3350 program // //See instructions on web page to produce a unit-test //for the normalize member function. // #include #include #include typedef double Flt; class Vec { private: Flt x; Flt y; public: Vec() { x = y = 0.0; } Vec(Flt a, Flt b) { x = a; y = b; } Flt getx() { return x; } Flt gety() { return y; } void make(Flt a, Flt b) { x = a; y = b; } Flt normalize() { //Normalize a vector. //Return the length of the vector. // //input: the components of a vector //output: the normalized vector length is returned // the vector argument is scaled to a length of 1.0 // //A degenerate vector may cause an error condition. //Length of 0.0 will be returned, //and a vector with length 1.0. // //calculate the vector dot product with itself ... Flt dot = x*x + y*y; //check for degenerate vector... if (dot == 0.0) { //set a vector of length 1.0 //printf("ERROR vector magnitude is zero.\n"); x = 1.0; y = 0.0; return 0.0; } //vector has a magnitude so continue. Flt len = sqrt(dot); Flt ooleng = 1.0 / len; x *= ooleng; y *= ooleng; return len; } }; //Array of vector values const Flt arr[] = { 1.0, 0.0, 1.0, 1.0, -1.2, 2.5, 99.9, 99.9, 2.2, -1.2, 0.0, 0.0 }; int main(int argc, char *argv[]) { //Program to calculate vector normalization and length. // printf(" \n"); printf("3350 Software Engineering \n"); printf(" \n"); printf("Calculation of vector lengths: \n"); printf(" \n"); printf(" x y length \n"); printf(" -------- -------- ---------- \n"); //read until sentinel found. int i=0; Vec vec( arr[i*2+0], arr[i*2+1] ); do { Flt ret = vec.normalize(); printf("%3i %8.5lf %8.5lf %10.5lf\n", i+1, arr[i*2+0], arr[i*2+1], ret); ++i; vec.make(arr[i*2+0], arr[i*2+1]); } while (!(vec.getx() == 0.0 && vec.gety() == 0.0)); // printf("\nProgram complete.\n\n"); return 0; }