Answer to Question #58424 in C++ for syed
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.
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
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";
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!