// // Program: english_to_metric // // Purpose: perform conversions from English-system units of distance // to their metric equivalents. // // Input/Output: // The program repeatedly prompts the user to enter one of the // following: // "i" for inches-to-centimeters conversion // "f" for feet-to-meters conversion // "m" for miles-to-kilometers conversion // "q" to quit // If the user enters "i", "f", or "m", the program prompts for the // distance, performs the conversion, and prints the result. // If the user enters "q", the program ends. // If the user enters any other character, the program prints an error // message (and prompts again). // #include #include // has EXIT_SUCCESS // See function definitions for comments. char getCommand(void); double getDistanceFromUser(void); double inches2cm(double i); double feet2m(double f); double miles2km(double m); // Main program. int main(void) { char cmd; // next "command" -- 'f', 'c', or 'q' do { cmd = getCommand(); if (cmd == 'i') cout << "That distance is " << inches2cm(getDistanceFromUser()) << " centimeters\n"; else if (cmd == 'f') cout << "That distance is " << feet2m(getDistanceFromUser()) << " meters\n"; else if (cmd == 'm') cout << "That distance is " << miles2km(getDistanceFromUser()) << " kilometers\n"; else if (cmd != 'q') cout << "Invalid response\n"; } while (cmd != 'q'); return EXIT_SUCCESS; } // Function to get the next command from the user. // Post: user has been prompted to enter "f", "c", or "q"; // returns user's response. char getCommand(void) { char response; cout << "Please choose what to do next:\n" << " i to convert inches to centimeters\n" << " f to convert feet to meters\n" << " m to convert miles to kilometers\n" << " q to quit\n" << "Your choice? "; cin >> response; return response; } // Function to prompt user for a distance to convert. // Post: user has been prompted to enter a distance; // returns user's response. double getDistanceFromUser(void) { double dist; cout << "Enter the distance to convert: "; cin >> dist; return dist; } // Function to convert inches to centimeters. // Pre: i is a distance in inches. // Post: returns equivalent distance in centimeters. double inches2cm(double i) { // 1 in = 2.54 cm return i * 2.54; } // Function to convert feet to meters. // Pre: f is a distance in feet. // Post: returns equivalent distance in meters. double feet2m(double f) { return inches2cm(f * 12) / 100; } // Function to convert miles to kilometers. // Pre: m is a distance in miles. // Post: returns equivalent distance in kilometers. double miles2km(double m) { return feet2m(m * 5280) / 1000; }