2014-04-11 63 views
0

我有一個包含數字的文件11 5 3 51,我試圖用掃描儀讀取文件,然後打印出該文件中最小的數字。但由於某種原因,當我運行下面的程序時,它會一直說「最小的數字是7」,並且我在考慮程序甚至從哪裏獲得第7個數字?沒有一個數字7在任何地方在文件或我的程序中,這個問題.....可能是什麼問題?使用掃描儀循環

from scanner import* 


def main(): 
    s = Scanner("data.txt") 
    items = ("data.txt") 
    i = s.readint() 
    ismallest = 0 
    for i in range(0,len(items),1): 
     if (items[i] < items[ismallest]): 
      ismallest = i 
    print ("the smallest number is", i) 

main() 
+0

其實你得到的最小號碼的索引 – locoyou

+0

'range(0,len(「data.txt」),1)'=='[0,1,2,3,4,5,6,7] ',你的循環從這個列表中獲得最後一項(7)。 ''data.txt「'是一個字符串,而不是文件。你的循環沒有做任何有用的事情(它把最小字母的索引放在字符串''data.txt「'in'ismallest'中,但你甚至不用那個變量)。 – x3al

回答

0

這是我要如何與open代替Scanner

content = []; 
with open("input.txt") as f: 
    content = f.readline().split() 

ismallest = int(content[0]) 

for i in range(0,len(content),1): 
    if (int(content[i]) < ismallest): 
    ismallest = int(content[i]) 

print ("the smallest number is", ismallest) 

編輯做到這一點:好吧,我想如果你想使用這個應該工作Scanner

s = Scanner("data.txt") 
items = [] 
currentInt = s.readint() 

while currentInt: 
    items.append(currentInt) 
    currentInt = s.readint() 

ismallest = items[0] 

for i in range(0,len(items),1): 
    if (items[i]) < ismallest): 
    ismallest = items[i] 

print ("the smallest number is", ismallest) 
+0

唯一的問題是明天我們的考試我的老師會讓我們使用掃描儀或他會給我一個0的程序 – FootOfGork

+0

@FootOfGork好的,對不起。看看我的編輯。我認爲這應該適合你。 – ryrich

0

在您的for循環中,您可以撥打for i in range...。您正在將i重新分配給range()

我複製你的代碼和for語句被稱作後添加print i正確的,它打印以下內容:

0 
1 
2 
3 
4 
5 
6 
7 
('the smallest number is', 7) 

因此,需要在一開始沒有你i = s.readint()的方面。我會建議重命名你的變量,你的錯誤應該去:)

此外,你可以只讀取文件,並拆分內容,並使用內置函數max()min()打印。