是否有一个内置函数可以像下面这样舍入?

10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20

当前回答

另一种方法(不需要显式的乘法或除法运算符):

def rnd(x, b=5):
    return round(x + min(-(x % b), b - (x % b), key=abs))

其他回答

这只是一个比例的问题

>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
...     int(round(b/5.0)*5.0)
... 
10
10
10
15
15
15
15
15
20
20
20

另一种方法(不需要显式的乘法或除法运算符):

def rnd(x, b=5):
    return round(x + min(-(x % b), b - (x % b), key=abs))

对于整数和Python 3:

def divround_down(value, step):
    return value//step*step


def divround_up(value, step):
    return (value+step-1)//step*step

生产:

>>> [divround_down(x,5) for x in range(20)]
[0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [divround_up(x,5) for x in range(20)]
[0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

去掉“rest”会起作用:

rounded = int(val) - int(val) % 5

如果该值是一个整数:

rounded = val - val % 5

作为函数:

def roundint(value, base=5):
    return int(value) - int(value) % int(base)

这是我的C代码。如果我理解正确的话,应该是这样的;

#include <stdio.h>

int main(){
int number;

printf("Enter number: \n");
scanf("%d" , &number);

if(number%5 == 0)
    printf("It is multiple of 5\n");
else{
    while(number%5 != 0)
        number++;
  printf("%d\n",number);
  }
}

这也是四舍五入到最接近5的倍数而不是四舍五入;

#include <stdio.h>

int main(){
int number;

printf("Enter number: \n");
scanf("%d" , &number);

if(number%5 == 0)
    printf("It is multiple of 5\n");
else{
    while(number%5 != 0)
        if (number%5 < 3)
            number--;
        else
        number++;
  printf("nearest multiple of 5 is: %d\n",number);
  }
}