//========================================================================= #define PROGRAMMER "SOLUTIONS, NoFrills" #define PROG_CODE "soln" #define COURSE "ECE-1021" #define YEAR (2003) #define TERM "Fall" #define SECTION (0) #define ASSIGNMENT "HW #2C" #define REVISION (0) #define TITLE "Rounding a Floating Point Value" #define SUBTITLE "Extra Credit" #define EMAIL "wbahn@eas.uccs.edu" #define FILENAME "02c0soln.c" //========================================================================= // PROBLEM: // // For a variable of type double (in Turbo C/C++ v4.5), round a value to // the number of decimal places requested by the user. The end result // should be reasonable for any possible value of the variable. // // PSEUDOCODE: (Developed in 02c0soln.c) // // 1) SET: f = floating point value to be rounded // 2) SET: n = number of decimal places // 3) SET: multiplier = 10^n // 4) IF: (f < 0) // 4.1) SET: multiplier = - multiplier // 5) SET: f = f * multiplier // 6) IF(f < 1e18) // 6.1) SET: digit1 = (long int) (f/1e9) // 6.2) SET: f = f - (digit1*1e9) // 6.3) SET: f = (long int) (f + 0.5) // 6.4) SET: f = f + (digit1*1e9) // 7) SET: f = f / multiplier //== INCLUDE FILES ======================================================== #include // printf() #include // pow() //== FUNCTION PROTOTYPES ================================================== void PrintHeader(void); //== MAIN FUNCTION ======================================================== int main(void) { double f; int n; double multiplier; long int digit1; PrintHeader(); printf("\n"); // Print a blank line printf("Enter a floating point value: "); scanf("%lf", &f); printf("Enter the number of decimal places: "); scanf("%i", &n); multiplier = pow(10, n); if(f < 0.0) multiplier *= -1.0; f *= multiplier; if(f < 1e18) { digit1 = (long int) (f/1e9); f -= digit1*1e9; f = (long int) (f + 0.5); f += digit1*1e9; } f /= multiplier; printf("The rounded number is: %20.20g\n", f); return(0); } //== SUPPORT FUNCTIONS ==================================================== void PrintHeader(void) { printf("========================================" "=======================================\n"); printf("Course....... %s-%i (%s %i)\n", COURSE, SECTION, TERM, YEAR); printf("Programmer... %s (%s)\n", PROGRAMMER, PROG_CODE); printf("Assignment... %s (Rev %i) (Source Code in %s)\n", ASSIGNMENT, REVISION, FILENAME); printf("Description.. %s\n", TITLE); printf(" %s\n", SUBTITLE); printf("========================================" "=======================================\n"); return; }