2013-07-16 2 views
-1

저는 파이썬을 처음 접했고 친구는 간단한 질문을 던졌습니다. ROUND와 같은 수학 연산을 사용하지 않고 숫자를 반올림하는 간단한 프로그램을 만드십시오. 저는 소수점 이하 자리 하나에 2.1이나 5.8과 같은 소수점 이하 자리 하나를 알아 내고 싶습니다. 나는 if/then 문과 같은 것임을 믿는다. - < 5면 do ..... do? 미리 감사드립니다 !!둥근 함수를 사용하지 않고 파이썬

+1

* some * math를 허용해야합니다. 심지어 문자열을 사용하고, 문자열 연산을 사용하고 그것을 다시 변환하려면 수학이 필요합니다. – user2357112

+0

'int ((my_num * 10) +0.5)/10.0' 또는''% 0.1f '% my_num_to_round' –

답변

2

(x이 번호) 이것에 대해 어떻게 :

정수로 반올림 :

int(x-0.5)+1 

가장 가까운 열 번째에 라운딩이 :

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

수학없이 그것을 그냥 사용 문자열 (여전히 수학을 사용함)

"%0.1f" % my_num_to_round 
0

다음은 매우 작은 수학을 사용하는 함수입니다 (더 크거나 같음 비교를 사용하는 것 외에는 프로그래머가 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) 
관련 문제