Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Rounding

#include "stdafx.h"

#include <iostream>

using namespace std;

 

//if an integer is converted to (stored as) a double, nothing is lost.

//if a double is converted to (stored as) an int, the fractional part is lost

 

int main()

{

   float d = 1234.4678;

   double e = 1234.5678;

   cout<<"Value of d: "<<d<<endl;

   cout<<"Value of e: "<<e<<endl;

   //rounding to nearest integer

   int f = d + .5;

   int g = e + .5;

   cout<<"d is rounded down to nearest integer as shown here: "<<f<<endl;

   cout<<"e is rounded up to nearest integer as shown here: "<<g<<endl;

   //rounding to nearest 2 decimal places - as for money calculations

   double h = d + .005;

   double i = h*100;

   int m = i;

   double p = m/100.0;

   cout<<"d rounded down is "<<p<<endl;

   cout<<"Same procedure works for rounding up"<<endl;

   return 0;

}