Let's define an integer r, which is what you insert into the blank in the following statement: "I want to round to the nearest ___".
The procedure for rounding to the nearest r is simple.
1: Add r/2. When you do an integer division like below, any remainder is truncated. This helps us get around that little issue and lets us do proper rounding (so that 15 would round to 20 and not 10 if you're rounding to the nearest 10).
2: Divide by r. This way, you're discarding all data that is less significant than r, essentially the goal of rounding. Can you see why?
3: Multiply by r to get your rounded integer. You're done!
Can you see why this works? If so, enjoy! If not, let us know.
constint r = 10; // "I want to round to the nearest 10 ".
int number;
cout << "Please enter an integer: " << endl;
cin >> number;
number += r/2; // 1: Add r/2.
number /= r; // 2: Divide by r.
number *= r; // 3: Multiply by r
cout << number << endl;
Well, I made it constant for two reasons. First, it indicates to the reader that I don't intend to change it. Secondly it is telling the compiler that I don't intend to change it. It helps in both respects. But no it isn't mandatory.
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
int data[] = { 15, 14, 4, 5, 99, 12345678, 44444445, 1445, 446 };
constint r = 10; // "I want to round to the nearest 10 ".
for (int i=0; i<sizeof(data)/sizeof(data[0]); i++)
{
int n = data[i];
cout << setw(8) << n << " ";
n += r/2; // 1: Add r/2.
n /= r; // 2: Divide by r.
n *= r; // 3: Multiply by r
cout << setw(8) << n << endl;
}
}
@kekiverto
U mean r should be changed with the number of digits.
But Its not efficient(specially for my code); since while r=10, it works for 2 digits number; and while r=100, it works for 3 digits number.
I need a common value of r or something another, which works for any case.
@chervil
Bro, U made 12345678 = 12345680; since r=10. But I need 12345678 = 10000000; as u did 14 = 10.
To generalize, have r as a non-constant. Then do.
r = 1;
if(n >= 10 && n < 100)
r = 10;
else if(n >= 100 && n < 1000)
r = 100;
else if(n >= 1000 && n < 10000)
r = 1000;
etc
You can even generalize those else ifs (by making a loop instead) if you want to.
#include <iostream>
#include <iomanip>
usingnamespace std;
int round(int n);
int main()
{
int data[] = { 15, 14, 4, 5, 99, -99, -14, -15, 12345678, 44444445, 1445, 446 };
for (int i=0; i<sizeof(data)/sizeof(data[0]); i++)
{
int n = data[i];
cout << setw(8) << n << " " << setw(8) << round(n) << endl;
}
}
int round(int n)
{
// "I want to round to the nearest r ".
int r = 1;
int temp = n;
while (temp/=10)
r *= 10;
n += r/2; // 1: Add r/2.
n /= r; // 2: Divide by r.
n *= r; // 3: Multiply by r
return n;
}