/* * Program to convert different kinds of "English" units to metric: * * Input: Which conversion is wanted, number to convert (program * prompts for these). Repeats prompt until user inputs 'x' to exit. * * Output: Result of conversion (e.g., inches to centimeters). */ #include /* has scanf(), printf() */ /* Constants for conversions. */ #define CM_PER_INCH 2.54 #define INCHES_PER_FOOT 12 #define FEET_PER_MILE 5280 #define CM_PER_M 100 #define KM_PER_M 1000 #define M_PER_FOOT \ (INCHES_PER_FOOT * CM_PER_INCH / CM_PER_M) #define KM_PER_MILE \ (FEET_PER_MILE * INCHES_PER_FOOT * CM_PER_INCH / (CM_PER_M * KM_PER_M)) /* Function declarations. (Comments with definitions, below main.) */ char getCommand(void); double getNumber(void); void convertInches(void); void convertFeet(void); void convertMiles(void); /* Main program */ int main(void) { char cmd; do { cmd = getCommand(); switch (cmd) { case 'i': convertInches(); break; case 'f': convertFeet(); break; case 'm': convertMiles(); break; case 'x': break; default: printf("Not a valid choice\n"); } } while (cmd != 'x'); return 0; } /* Function definitions. */ /* Prompt user for menu selection and return result. */ char getCommand(void) { char cmd; printf("What would you like to do?\n"); printf(" 'i' to convert inches to centimeters\n"); printf(" 'f' to convert feet to meters\n"); printf(" 'm' to convert miles to kilometers\n"); printf(" 'x' to exit\n"); printf("Your choice?\n"); scanf(" %c", &cmd); /* space before %c says "skip leading white space" */ return cmd; } /* Get number from standard input. Prints error message and prompts * again if non-numeric input is provided. */ double getNumber(void) { double number; char c; /* keep trying to get input until we get something valid */ while (scanf("%lf", &number) != 1) { /* not a number -- discard input until we get to end of line */ do { scanf("%c", &c); } while (c != '\n'); printf("Not a number. Please try again:\n"); } return number; } /* Do "inches to cm" conversion (prompt for input, print result). */ void convertInches(void) { double inches; printf("how many inches?\n"); inches = getNumber(); printf("%lf inches is %lf cm\n", inches, CM_PER_INCH * inches); } /* Do "feet to meters" conversion (prompt for input, print result). */ void convertFeet() { double feet; printf("how many feet?\n"); feet = getNumber(); printf("%lf feet is %lf m\n", feet, M_PER_FOOT * feet); } /* Do "miles to km" conversion (prompt for input, print result). */ void convertMiles() { printf("miles\n"); double miles; printf("how many miles?\n"); miles = getNumber(); printf("%lf miles is %lf cm\n", miles, KM_PER_MILE * miles); }