-1

我是 Python 新手,一个朋友向我提出了一个让我很困惑的简单问题:请为我构建一个简单的程序,它可以在不使用任何数学运算(如 ROUND)的情况下对数字进行舍入。我只想计算出一个小数位——比如 2.1 或 5.8——长小数位没什么特别的。我相信这有点像 if/then 语句 - if < 5 then do.....做什么?先感谢您!!

4

3 回答 3

4

这个怎么样(x你的电话号码在哪里):

四舍五入为整数:

int(x-0.5)+1

四舍五入到最接近的十分之一:

(int(10*x-0.5)+1) / 10.0
于 2013-07-16T01:13:19.627 回答
4

不用数学就可以使用字符串(它仍然使用数学)

"%0.1f" % my_num_to_round
于 2013-07-16T01:17:50.047 回答
-2

这是一个使用很少数学运算的函数(除了使用大于或等于比较之外,唯一的数学运算是程序员为创建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)
于 2013-07-17T18:58:05.610 回答