2017-04-07 79 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

相关问题