algorithm - C++: Rounding up to the nearest multiple of a number -
OK - I'm almost embarrassed to post it here (and I'll delete if I vote off any votes) .
Is this the correct way to score more than one number in C ++?
I know there are other questions related to this, but I am quite interested in knowing what is the best way to do it in C ++:
< Code> int roundUp (int numToRound, Int multiple) {if (multiple == 0) {return numToRound; } Int roundDown = ((int) (numToRound) / multiple) * multiple; Int roundUp = roundDown + multiple; Int roundCalc = roundUp; Return (goaltrap); }
Update: Sorry, maybe I did not clear the intention here. Here are some examples:
roundup (7, 100) // return 100 Roundup (117, 100) // Return 200 Roundup (477, 100) // Returns 500 Roundups (1077, 100) // Return 1100 Roundups (52, 20) // Return 60 Roundups (74, 30) // Return 90
Edit: Thanks for all the replies. This is what I went for:
int roundUp (int numToRound, int multiple) {if (multiple == 0) {return numToRound; } Int balance = numToRound% multiple; If (balance == 0) {return to numToRound; } Return number; Over + equal - remaining; }
This works for positive numbers, not sure about the negative It uses only integer mathematics.
int roundUp (int numToRound, int multiple) {if (multiple == 0) numToRound; Int balance = numToRound% multiple; If (balance == 0) returns back; Return nanteround + multiple - remaining; }
Edit: This is a version that works with negative numbers, if "above" means you always> input =. Input
int roundup (int newtoround, int multiple) {if (multiple == 0) numToRound; Int balance = abs (numToRound)% multiple; If (balance == 0) returns back; If (numToRound & lt; 0) return - (abs (numToRound - left)); And then numToRound + multiple - remainder; }