// Zeinalipour-Yazti Demetrios // csyiazti // cs10xx - Lab Sec#25-#29 // lab8 /* * This program defines a function that finds and returns the distance between * two points. The function should take as parameters the x and y coordinates * of point1 and the x an y coordinates of point2. The coordinates are * floating-point values. The program allows the user to find the distance * between as many points as they want. Each output is outputted as a * floating-point value showing 3 digits to the right of the decimal. */ #include #include #include using namespace std; /* Get value from user along with error checking etc * @return : the FLOAT value given by the user */ float getfloat(char name[]) { float val; cout << "Please enter floating point value (" << name << ") : "; cin >> val; while (cin.fail()) { cout << "#ERROR - Only floating point values are allowed!\n"; cin.clear(); cin.ignore(80, '\n'); cout << "Please enter floating point value (" << name << ") :"; cin >> val; } return val; } /* This function returns us the distance between 2 points * @return : the distance bete number */ float distance(float x1, float y1, float x2, float y2) { double temp1 = pow(x2-x1, 2); double temp2 = pow(y2-y1, 2); // return the result of the given formula return sqrt(temp1+temp2); } /* This function asks the user to select the char "y" or "n" * @return : y for yes * n for no */ char doAgain() { /* defining local scope variables*/ char value; cout << "\nDo you want to run the program again (y/n) ?: "; cin >> value; while (cin.fail() || !(value=='y' || value=='n')) { cout << "#Error - only (y/n) are accepted!\n"; cin.clear(); cin.ignore(80, '\n'); cout << "Do you want to run the program again (y/n) ? : "; cin >> value; } cout << endl; return value; } void main() { /* define variables */ float result; /* the result */ float x1, y1, x2, y2; /* the coordinates of point1, point2 respectively */ /* define functions & procedures*/ float getfloat(char name[]); /* get a correct float value from user */ float distance(float x1, float y1, float x2, float y2); char doAgain(); /* returns 'y' or 'n' to the question whether to continue */ cout << "Distance Calculator by Demetris Zeinalipour - Lab 8 \n\n"; // run the program as many times as the user wants do { // get the input from user in a function-fashion way x1 = getfloat("x1"); y1 = getfloat("y1"); x2 = getfloat("x2"); y2 = getfloat("y2"); /* calculate the result*/ result = distance(x1, y1, x2, y2); // output result cout << setprecision(3) << setiosflags(ios::fixed | ios::showpoint) << "\n\nThe distance of (" << x1 << "," << y1 << ") to (" << x2 << "," << y2 << ") is : " << result; } while (doAgain()=='y'); }