Python 不带圆函数的圆函数

Python 不带圆函数的圆函数,python,rounding,Python,Rounding,我是Python新手,一位朋友向我提出了一个简单的问题,这个问题让我困惑不解:请为我构建一个简单的程序,不使用任何数学运算(如ROUND)对数字进行取整。我只想计算出一个小数位,比如2.1或5.8,没有长的小数位。我觉得这有点像if/then语句——如果

我是Python新手,一位朋友向我提出了一个简单的问题,这个问题让我困惑不解:请为我构建一个简单的程序,不使用任何数学运算(如ROUND)对数字进行取整。我只想计算出一个小数位,比如2.1或5.8,没有长的小数位。我觉得这有点像if/then语句——如果<5,那么做……做什么?提前谢谢你

这个怎么样,其中x是你的号码:

四舍五入到整数:

int(x-0.5)+1
四舍五入至最接近的十分之一:

(int(10*x-0.5)+1) / 10.0

不用数学,只需使用字符串,它仍然使用数学

"%0.1f" % my_num_to_round

这里有一个函数,除了使用大于或等于的比较外,它只使用很少的数学运算,唯一的数学运算是由程序员创建nxt_int函数。我认为唯一的限制是,尽管小数的长度没有限制,但只能舍入小数

input = 2.899995

def nxt_int(n): # Get the next consecutive integer from the given one
    if n == '0':
        n_out = '1'
    elif n == '1':
        n_out = '2'
    elif n == '2':
        n_out = '3'
    elif n == '3':
        n_out = '4'
    elif n == '4':
        n_out = '5'
    elif n == '5':
        n_out = '6'
    elif n == '6':
        n_out = '7'
    elif n == '7':
        n_out = '8'
    elif n == '8':
        n_out = '9'
    elif n == '9':
        n_out = '0'
    return n_out

def round(in_num):
    # Convert the number to a string
    in_num_str = str(in_num)
    # Determine if the last digit is closer to 0 or 10
    if int(in_num_str[-1]) >= 5:
        # Eliminate the decimal point
        in_num_str_split = ''.join(in_num_str.split('.'))
        # Get the length of the integer portion of the number
        int_len = len(in_num_str.split('.')[0])
        # Initialize the variables used in the loop
        out_num_str = ''
        done = False
        # Loop over all the digits except the last digit in reverse order
        for num in in_num_str_split[::-1][1:]:
            # Get the next consecutive integer
            num_nxt_int = nxt_int(num)
            # Determine if the current digit needs to be increased by one
            if (num_nxt_int == '0' or num == in_num_str_split[-2] or out_num_str[-1] == '0') and not done:
                out_num_str = out_num_str + num_nxt_int
            else:
                out_num_str = out_num_str + num
                done = True
        # Build the rounded decimal
        out_num_str = (out_num_str[::-1][:int_len] + '.' + out_num_str[::-1][int_len:]).rstrip('0').rstrip('.')
    else:
        # Return all except the last digit
        out_num_str = in_num_str[:-1]
    return out_num_str

print round(input)
你必须允许一些数学知识。即使使用字符串操作对其进行字符串化,并将其转换回,也需要数学运算