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
yields:
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.
1
Expert's answer
2016-03-18T15:48:04-0400
#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: ";
Comments
Leave a comment