/* * Program to convert different kinds of "English" units to metric: * * Input: Which conversion is wanted, number to convert (program * prompts for these). * * Output: Result of conversion (e.g., inches to centimeters). */ #include /* has scanf(), printf() */ #include /* has exit() */ /* 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; 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"); } 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); return cmd; } /* Get number from standard input. Prints error message and exits * program if non-numeric input is provided. (This might not be the * best thing to do, but the main point of this function is to * illustrate using a function to avoid duplicating code.) */ double getNumber(void) { double number; if (scanf("%lf", &number) == 1) { return number; } else { printf("Not a number\n"); exit(0); } } /* 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); }