C++ || Snippet – Round A Number To The Nearest Whole Number
This page will display a simple implementation of a function which rounds a floating point number to the nearest whole number. So for example, if the number 12.34542 was sent to the function, it would return the rounded value of 12.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <cmath> using namespace std; // function prototype double RoundNumber(double floatNumber); int main() { // declare variables double floatNumber = 0; cout<<"Enter in a floating point number to round: "; cin >> floatNumber; cout<<endl<<floatNumber<<" rounded to the nearest " "whole number is: "<< RoundNumber(floatNumber)<<endl; return 0; } double RoundNumber(double floatNumber) { // declare variables double intNumber = 0; // perform modulus (floatNumber % intNumber) // to render the decimal portion of the floatNumber double fraction = modf(floatNumber,&intNumber); // we round up if fraction >=.50 if(fraction >=.50) { ++intNumber; } return intNumber; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
(Note: the code was compile three separate times to display different output)
====== RUN 1 ======
Enter in a floating point number to round: 1.3333
1.3333 rounded to the nearest whole number is: 1
====== RUN 2 ======
Enter in a floating point number to round: 35.56
35.56 rounded to the nearest whole number is: 36
====== RUN 3 ======
Enter in a floating point number to round: 19.8728
19.8728 rounded to the nearest whole number is: 20
Leave a Reply