2014-10-01 92 views
0

我是Python的初學者。我正在學習python上大學。使用函數內的小數時遇到問題

我正在創建一個程序來查找使用函數的平均值,中值和模式。還沒有開始模式。

問題:如果代碼中有小數(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 – 2014-10-01 03:21:33

+0

這是因爲你只是通過整數除法得到中間元素('len(numbers)// 2');如果你想取中間兩個元素的平均值,那麼當長度是偶數時,你需要一個特例。 – caseygrun 2014-10-01 04:38:06

+0

可以請你給我一些代碼去掉。我不確定我是否明白。 – 2014-10-01 04:43:30