(Rounding Numbers) Function floor can be used to round a number to a specific decimal
place. The statementy = floor( x * 10 + .5 ) / 10;
rounds x to the tenths position (the first position to the right of the decimal point). The statement y = floor( x * 100 + .5 ) / 100; rounds x to the hundredths position (the second position to the right of the decimal point). Write a program that defines four functions to round a number x in various ways:
a) roundToInteger( number )
b) roundToTenths( number )
c) roundToHundredths( number )
d) roundToThousandths( number )
For each value read, your program should print the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.
Solution:
place. The statementy = floor( x * 10 + .5 ) / 10;
rounds x to the tenths position (the first position to the right of the decimal point). The statement y = floor( x * 100 + .5 ) / 100; rounds x to the hundredths position (the second position to the right of the decimal point). Write a program that defines four functions to round a number x in various ways:
a) roundToInteger( number )
b) roundToTenths( number )
c) roundToHundredths( number )
d) roundToThousandths( number )
For each value read, your program should print the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth and the number rounded to the nearest thousandth.
Solution:
#include<iostream> using namespace std; int roundToInteger( double ); double roundToTenths( double ); double roundToHundredths( double ); double roundToThousandths( double ); double number; int main() { cout << "Enter number to round (EOF to end): "; cin >> number; while( number != EOF ) { cout << roundToInteger( number ) << endl << roundToTenths( number ) << endl << roundToHundredths( number ) << endl << roundToThousandths( number ) << endl; cout << "Enter number to round (EOF to end): "; cin >> number; } //for pause system("PAUSE"); return 0; } //rounding int roundToInteger( double number ) { return floor( number + .5 ); } double roundToTenths( double number ) { return floor( number * 10 + .5) / 10; } double roundToHundredths( double number ) { return floor( number * 100 + .5) / 100; } double roundToThousandths( double number ) { return floor( number * 1000 + .5) / 1000; }
Post A Comment:
0 comments: