/* * 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. * (Here I chose to compute everything from English-to-English, * metric-to-metric, and inches-to-centimeters factors, because * that seemed more likely to be as accurate as possible. But * could have just looked up the needed conversion factors somewhere. */ #define CM_PER_INCH 2.54 #define INCHES_PER_FOOT 12 #define FEET_PER_MILE 5280 #define CM_PER_M 100 #define M_PER_KM 1000 /* m/ft = in/ft * cm/in * m/cm = (in/ft * cm/in) / (cm/m) */ #define M_PER_FOOT \ (INCHES_PER_FOOT * CM_PER_INCH / CM_PER_M) /* km/mi = ft/mi * in/ft * cm/in * km/cm = (ft/mi * in/ft * cm/in) / (cm/m * m/km) */ #define KM_PER_MILE \ (FEET_PER_MILE * INCHES_PER_FOOT * CM_PER_INCH / (CM_PER_M * M_PER_KM)) /* Function declarations. (Comments with definitions, below main.) */ char getCommand(void); float 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.) */ float getNumber(void) { float number; if (scanf("%f", &number) == 1) { return number; } else { printf("Not a number\n"); exit(1); } } /* Do "inches to cm" conversion (prompt for input, print result). */ void convertInches(void) { float inches; printf("how many inches?\n"); inches = getNumber(); printf("%f inches is %f cm\n", inches, CM_PER_INCH * inches); } /* Do "feet to meters" conversion (prompt for input, print result). */ void convertFeet() { float feet; printf("how many feet?\n"); feet = getNumber(); printf("%f feet is %f m\n", feet, M_PER_FOOT * feet); } /* Do "miles to km" conversion (prompt for input, print result). */ void convertMiles() { printf("miles\n"); float miles; printf("how many miles?\n"); miles = getNumber(); printf("%f miles is %f cm\n", miles, KM_PER_MILE * miles); }