2014-10-01 4 views
0

저는 파이썬에서 초보자입니다. 나는 대학을 위해 파이썬을 배우고있다.함수 내 소수점에 문제가 있습니다.

나는 함수를 사용하여 평균, 중앙값 및 모드를 찾기위한 프로그램을 만들고 있습니다. 아직 모드로 가지 않았어.

: 코드에 소수점이있는 경우 두 기능 모두 컴퓨팅에 문제가 있습니다 (1.2, 1.3, 7.423 등). 중앙값은 소수를 의미하는 경우 중앙값 함수는 숫자를 반올림합니다.

모드를 계산하는 방법을 파악하는 것도 어렵습니다. 누군가가 저를 도울 수 있으면, 그것은 굉장 할 것입니다.

도움을 주셔서 감사합니다. 이번이 처음 게시됩니다.

#instructions for user 
print ("This program is designed to calculate mean, median, and mode.") 
print ("I need you to type the numbers you desire to be calculated.") 
print ("") 
print ("NOTICE: Use the spacebar to separate your numbers.") 
print ("") 
print ("NOTICE: Press enter to finalize your numbers list.") 
print ("") 

#creates list of numbers 
s = raw_input("Begin typing: ") 
numbers = map(int, s.split()) 

#instructions for user 
print "" 
print "Type 'mean()' to calculate for mean." 
print "Type 'median()' to calcuate for median." 
print "" 

#creates mean function 
def mean(): 
    print "the mean is: " + str(sum(numbers)/len(numbers)) 

#creates median function 
def median(): 
    print "the median is: " + str(sorted(numbers)[len(numbers)//2]) 

답변

0
numbers = map(int, s.split()) 

int 가장 가까운 정수로 반올림, 각 숫자를 잘라 사용 : 여기

는 코드입니다. 소수점을 처리하려면 float을 사용하십시오.

numbers = map(float, s.split()) 
+0

감사합니다. 이것은 나의 평균 기능을 크게 수정합니다. 중간 값 함수를 사용할 때 나는 여전히 문제가 있습니다. 만약 내가 1 2 3 4를 내 목록으로 입력한다면 나의 중간 값은 3.0으로 잘못 나온다. 그것은 2.5 –

+0

이어야합니다. 왜냐하면 당신은 정수 부분 ('len (numbers) // 2')에 의해 중간 요소를 얻고 있기 때문입니다; 가운데 두 요소의 평균을 취하고 싶다면 길이가 짝수 일 때 특별한 경우가 필요합니다. – caseygrun

+0

나에게 약간의 코드를 제공 해줄 수 있습니까? 나는 정확하게 이해하고 있는지 확신 할 수 없다. –

관련 문제