The following is an extremely useful programming algorithm for rounding a real n
ID: 3799690 • Letter: T
Question
The following is an extremely useful programming algorithm for rounding a real number to n decimal places: Step 1: Multiply the number by 10^n step 2: Add 0.5 Step 3: Delete the fractional part of the result Step 4: Divide by 10^n For example, using this algorithm to round the number 78.374625 to three decimal places yields: Seep 1:78.374625 times 10^3 = 78374.625 Step 2: 78374.625 + 0.5 = 78375.125 Step 3: Retaining the integer part = 78375 Step 4: 78375 divided by 10^3 = 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. Enter, compile, and the program written for Exercise 11a.Explanation / Answer
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
//get input
double x;
cout << "Enter decimal value: ";
cin >> x ;
int roundLength;
cout << "Round till how many digits? ";
cin >> roundLength ;
//multiply by 10^n
double multiplicationFactor = pow(10, roundLength);
x = x * multiplicationFactor;
//add 0.5
x = x + 0.5f;
//integer part
int integerPart = (int) x;
//divide by 10^n
x = integerPart / multiplicationFactor;
cout << "Rounded value is: " << x << endl;
return 0;
}
====sample output====
Enter decimal value: 78.374625
Round till how many digits? 2
Rounded value is: 78.37
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.