2017-04-07 76 views
0

本質上,我想將所有用戶輸入保存到數組中,並在用戶輸入0時添加它們。我不知道該怎麼做。在我的腳本中,每次都不可避免地改變x值。將用戶輸入值保存到數組中

這裏是我的腳本至今:

print("This program will sum a series of numbers.") 
x <- 1:100  
num <- c(x) 
while (num[x] != 0) { 
    print("Enter the next number (enter 0 when finished)") 
    num[x] <- as.numeric(readLines(con=stdin(),1)) 
} 
sum <- sum(num) 
print(paste("The sum of your numbers is", sum)) 

我得到這個錯誤:

In while (num[x] != 0) { : the condition has length > 1 and only the first element will be used

有人可以幫我嗎?

回答

1

這裏是一個可能的解決方案:

print("This program will sum a series of numbers.") 
next_entry <- 1 
entries <- vector() 
while (next_entry != 0) { 
print("Enter the next number (enter 0 when finished)") 
next_entry <- as.numeric(readLines(con=stdin(),1)) 
entries <- c(entries, next_entry) 
} 
sum <- sum(entries) 
print(paste("The sum of your numbers is", sum)) 

與你的腳本的問題是,「NUM」已經被定義,因爲你把它設置爲1:100的3號線。

+0

哇!非常感謝。 – Tina

相關問題