How do I find the next multiple of 10 of any integer?

后端 未结 12 1128
Happy的楠姐
Happy的楠姐 2020-12-08 04:15

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.

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 04:49

    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;
    }
    

提交回复
热议问题