68 322
Assignments Done
Successfully Done
In November 2018

Answer to Question #58424 in C++ for syed

Question #58424
The following is a useful programming algorithm for rounding a real number to
n decimal places:
Step 1: Multiply the number by 10n.
Step 2: Add 0.5.
Step 3: Delete the fractional part of the result.
Step 4: Divide by 10n.
For example, using this algorithm to round the number 78.374625 to three decimal places
Step 1: 78.374625 × 103 = 78374.625
Step 2: 78374.625 + 0.5 = 78375.125
Step 3: Retaining the integer part = 78375
Step 4: 78375 divided by 103 = 78.375
Using this algorithm, write a C++ function that accepts a user-entered value and returns the
result rounded to two decimal places.
b. Include the function written in Exercise 16a in a working program. Make sure your function
is called from main() and returns a value to main() correctly. Have main() use a cout
statement to display the returned value. Test the function by passing various data to it and
verifying the returned value.
Expert's answer
#include <math.h>
#include <iostream>

using namespace std;

double round_number(double number, int n)
double result = 0;
result = number * pow(10, n); //Step 1
result += 0.5; //Step 2
result = (int)result; //Step 3
result /= pow(10, n); //Step 4
return result;

int main()
double n;
double x;
cout << "This program is for rounding a real number to n decimal places\n";
cout << "Enter n: ";

cin >> n;
cout << "Enter real number: ";

cin >> x;
double result = round_number(x, n);
cout << "Rounded number: " << result << "\n";
return 0;

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be first!

Leave a comment

Ask Your question

Privacy policy Terms and Conditions