Sunday, August 14, 2011

Round Off

Problem:   Round off a given decimal number to two decimal places.


Algorithm:
1. Input the decimal number.
2. Separate its integer part.
3. Subtract the integer part from the given number to get the fraction.
4. Multiply the fraction by 1000 (we need first 3 digits after the decimal point)
5. Find the third digit of this number by taking mode with 10.
6. If this digit is greater than or equal to 5, add 0.01 to the original decimal number else leave it as it is.
7. Set the precision to show two digits after the decimal point and display the result.

Source Code:
#include<iostream>
#include<iomanip>
#include<conio.h>
using namespace::std;
int main(void)
{
int integer;
int num;
double decimal;
double fraction;
cout<<"Enter the decimal number: ";
cin>>decimal; //Input the decimal number
integer=decimal; //Separating the integer part
fraction=decimal-integer;  //Separating the fraction part
num=(fraction*1000); // % operator in next step works only with integers
num=num%10; //Finding the 3rd digit after decimal point
cout<<fixed<<showpoint;
if(fraction>=5)
{
cout<<"Given decimal number rounded to two decimal places is: ";
cout<<setprecision(2)<<decimal+0.01<<endl;
}
else
{
cout<<"Given decimal number rounded to two decimal places is: ";
cout<<setprecision(2)<<decimal<<endl;
}
getch();
return 0;
}


This program is working fine with any kind of input. Let me know if you think something is wrong...



0 response(s):

Respond to this Post

Your participation is appriciated...