How do I find the next multiple of 10 of any integ

2020-02-07 18:21发布

Dynamic integer will be any number from 0 to 150.

i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10.

Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?
Only thing is would also have to know if the number is 1, 2 or 3 digits (i.e. - 7 vs 94 vs 136)

Is there a better way to achieve this?

Thank You,

标签: c algorithm math
12条回答
We Are One
2楼-- · 2020-02-07 18:31

What about ((n + 9) / 10) * 10 ?

Yields 0 => 0, 1 => 10, 8 => 10, 29 => 30, 30 => 30, 31 => 40

查看更多
We Are One
3楼-- · 2020-02-07 18:33

How about using integer math:

N=41
N+=9   // Add 9 first to ensure rounding.
N/=10  // Drops the ones place
N*=10  // Puts the ones place back with a zero
查看更多
混吃等死
4楼-- · 2020-02-07 18:33

in C, one-liner:

int inline roundup10(int n) {
  return ((n - 1) / 10 + 1) * 10;
}
查看更多
劫难
5楼-- · 2020-02-07 18:36

You can do this by performing integer division by 10 rounding up, and then multiplying the result by 10.

To divide A by B rounding up, add B - 1 to A and then divide it by B using "ordinary" integer division

Q = (A + B - 1) / B 

So, for your specific problem the while thing together will look as follows

A = (A + 9) / 10 * 10

This will "snap" A to the next greater multiple of 10.

The need for the division and for the alignment comes up so often that normally in my programs I'd have macros for dividing [unsigned] integers with rounding up

#define UDIV_UP(a, b) (((a) + (b) - 1) / (b))

and for aligning an integer to the next boundary

#define ALIGN_UP(a, b) (UDIV_UP(a, b) * (b))

which would make the above look as

A = ALIGN_UP(A, 10);

P.S. I don't know whether you need this extended to negative numbers. If you do, care should be taken to do it properly, depending on what you need as the result.

查看更多
地球回转人心会变
6楼-- · 2020-02-07 18:43

You could do the number mod 10. Then take that result subtract it from ten. Then add that result to the original.

if N%10 != 0  #added to account for multiples of ten 
  a=N%10
  N+=10-a
查看更多
趁早两清
7楼-- · 2020-02-07 18:48

Be aware that answers based on the div and mod operators ("/" and "%") will not work for negative numbers without an if-test, because C and C++ implement those operators incorrectly for negative numbers. (-3 mod 5) is 2, but C and C++ calculate (-3 % 5) as -3.

You can define your own div and mod functions. For example,

int mod(int x, int y) {
  // Assert y > 0
  int ret = x % y;
  if(ret < 0) {
    ret += y;
  }
  return ret;
}
查看更多
登录 后发表回答