2016-10-15 35 views
0

我是一個使用ipython筆記本和熊貓在線課程的初學者。這個函數會返回一個以百萬爲單位的舍入數字會出什麼問題

我們給出一個函數

def roundToMillions (value): 
    result = round(value/1000000) 
    return result 

和一些測試

roundToMillions(4567890.1) == 5 

roundToMillions(0) == 0 # always test with zero... 

roundToMillions(-1) == 0 # ...and negative numbers 

roundToMillions(1499999) == 1 # test rounding to the nearest 

我們被告知.. 定義了幾個測試用例兩種功能

雖然我想不出任何更多的測試。

提出的問題是:

爲什麼你不能使用roundToMillions()人口舍入到數以百萬計的居民?

我不太明白這個函數有什麼問題。

本課程是免費的,所以沒有太多的幫助。

回答

0

在測試用例而言,這個循環將產生許多測試案例和結果不言自明:

for x in xrange(-2000000, 2000000, 250000): 
print roundToMillions(x), x 
>> -2.0 -2000000 
>> -2.0 -1750000 
>> -2.0 -1500000 
>> -2.0 -1250000 
>> -1.0 -1000000 
>> -1.0 -750000 
>> -1.0 -500000 
>> -1.0 -250000 
>> 0.0 0 
>> 0.0 250000 
>> 0.0 500000 
>> 0.0 750000 
>> 1.0 1000000 
>> 1.0 1250000 
>> 1.0 1500000 
>> 1.0 1750000 

所以,很顯然它捨去。

這是由於整數除法。去除輪顯示了這個:

def roundToMillions (value): 
    result = value/1000000 
    return result 
print roundToMillions(999999) 
>> 0 

這是通過添加一個1.0到功能固定:

def roundToMillions (value): 
    result = round(value/1000000.0) 
    return result 

for x in xrange(0, 1000000, 250000): 
    print roundToMillions(x), x 
>> 0.0 0 
>> 0.0 250000 
>> 1.0 500000 
>> 1.0 750000 
print roundToMillions(999999) 
>> 1.0 

更多關於整數除法看看

print (3/2) 
>> 1 
print (3.0/2.0) 
>> 1.5 
+0

謝謝您幫助丹尼爾。 – jondonut

+0

謝謝丹尼爾。在你的代碼1750000下降到1右? – jondonut

+0

當我運行roundToMillions(1750000)返回的答案值是2 – jondonut

相關問題