2016-03-06 55 views
-2

我試圖編寫一個函數,該函數將用戶輸入的整數序列作爲輸入並返回累計總數。例如,如果輸入是1 7 2 9,則該函數應打印1 8 10 19。我的程序無法正常工作。下面是代碼:來自用戶輸入字符串的累計總數

x=input("ENTER NUMBERS: ") 
total = 0 
for v in x: 
    total = total + v 
    print(total) 

這裏是輸出:

ENTER NUMBERS: 1 2 3 4 

Traceback (most recent call last): 
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module> 
total = total + v 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

我不知道這是什麼錯誤表示。請幫我調試我的代碼。

+0

看看你的錯誤信息:'類型錯誤:不支持的操作數類型(S)爲+: '詮釋' 和「str''。這意味着什麼是一個問題,你可以採取哪些步驟來理解和解決它? – hexafraction

+0

你可以請你的問題重新說一下嗎?就像這樣,它聽起來有點像[gimme teh codez](http://meta.stackoverflow.com/questions/288133/is-using-stack-overflow-for-gimme-codez-questions-encouraged)問題,這些網站不鼓勵這些內容。但是,高質量的問題會讓您獲得聲望,從而爲您提供更多的網站權限。 – wizzwizz4

+0

不要讓downvotes不鼓勵你,你可以改善這個問題。只需點擊[編輯](http://stackoverflow.com/posts/35827634/edit)按鈕即可。 – wizzwizz4

回答

0

此代碼將工作。記住:閱讀代碼並瞭解它是如何工作的。

x = input("Enter numbers: ") #Take input from the user 
list = x.split(" ")   #Split it into a list, where 
          #a space is the separator 
total = 0     #Set total to 0 
for v in list:    #For each list item 
    total += int(v)   #See below for explanation 
    print(total)    #Print the total so far 

有代碼中有兩處新的東西:

  • x.split(y)分裂x成更小的字符串列表,使用y作爲分隔符。例如,"1 7 2 9".split(" ")返回[「1」,「7」,「2」,「9」]。
  • total += int(v)比較複雜。我將分解更多:
    • split()函數給了我們一串字符串,但我們需要數字。 int()函數(除其他外)將字符串轉換爲數字。這樣,我們可以添加它。
    • +=運算符表示「增加」。寫作x += y與寫作x = x + y相同,但輸入時間較短。

有一個與代碼另一個問題:你說你需要的功能,但是這是不是一個函數。函數可能是這樣的:

function cumulative(list): 
    total = 0 
    outlist = [] 
    for v in list: 
     total += int(v) 
     outlist.append(total) 
    return outlist 

,並使用它:

x = input("Enter numbers: ").split(" ") 
output = cumulative(x) 
print(output) 

但程序會工作得很好。

+0

感謝BRO ..它工作完美.. U解決了我的問題:) –

+0

不客氣。在你的問題的每個答案旁邊都有一個勾號。將標記作爲答案的答案放在最好的答案旁邊。 – wizzwizz4

+0

並記住:不要只問;也回答! :-) – wizzwizz4

0

累加總數

input_set = [] 
input_num = 0 

while (input_num >= 0): 

    input_num = int(input("Please enter a number or -1 to finish")) 
    if (input_num < 0): 
     break 
    input_set.append(input_num) 

print(input_set) 

sum = 0 
new_list=[] 

for i in range(len(input_set)): 
    sum = sum + input_set[i] 
    new_list.append(sum) 

print(new_list)