rounding in c++

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
Randi
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 50
Joined: Sat Apr 24, 2010 1:32 pm
Location: Noobville

rounding in c++

Post by Randi »

I am trying to round a number to the nearest 5 or 10, is there any easy way of doing this?

for example: I have the number 44, it would round to 45.
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: rounding in c++

Post by Ginto8 »

Code: Select all

int roundToNrst5(int x) {
    int y = x%5;
    if(y>2 || y == 0)
        return x+(5-y);
    else
        return x-y
}
% is modulus (remainder of division). Aside from that you should be able to figure it out. ;)
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
Randi
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 50
Joined: Sat Apr 24, 2010 1:32 pm
Location: Noobville

Re: rounding in c++

Post by Randi »

Thank you very much Ginto!
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: rounding in c++

Post by Ginto8 »

Randi wrote:Thank you very much Ginto!
no problem, always glad to help ;)
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
Post Reply