Thursday, March 15, 2012

Rounding Numbers

The statement y = floor( x + .5 ); will round the number x to the nearest integer and assign the result to y. Reads a number and print the original number and the rounded number.

/*
   title: roundingNumbers
   author: aeriqusyairi
   date: Jan22 2012
   source: exercise 5.10 Chapter 5
*/
#include<stdio.h>
#include<math.h>

double roundToInteger(double);
double roundToTenths(double);
double roundToHundreths(double);
double roundToThousandths(double);

int main(){
   float number = 0;
   printf("Enter a number to round:"); 
   scanf("%f", &number);
   
   printf("Original number: %.5f\n", number);
   printf("Round to nearest integer: %.5lf\n", roundToInteger(number));
   printf("Round to nearest tenths: %.5lf\n", roundToTenths(number));
   printf("Round to nearest hundreths: %.5lf\n", roundToHundreths(number));
   printf("Round to nearest thousandths: %.5lf\n", roundToThousandths(number));
   
   
   system("pause");
   return 0;      
}

double roundToInteger(double toRound){
   return floor(toRound + .5);       
}

double roundToTenths(double toRound){
   return floor(toRound * 10 + .5) / 10;    
}

double roundToHundreths(double toRound){
   return floor(toRound * 100 + .5) / 100;        
}

double roundToThousandths(double toRound){
   return floor(toRound * 1000 + .5) / 1000;        
}

No comments:

Post a Comment