I am trying to write a program that will ask the user for an integer and calculate the integer's factorial and the program will end if the user gives a negative number. I get an
Error in while (x >= 0) { : missing value where TRUE/FALSE
needed and sometimes this
Error in x + 1 : non-numeric argument to binary operator
My code:
x <-readline(prompt="Enter an integer: ")
x <- as.integer(x)
while(x >= 0)
{
y <- factorial(x)
y
x <-readline(prompt="Enter an integer: ")
x <- as.integer(x)
}
Your code will work if you put everything inside a function. I improved your code and created a function myfun
.
myfun <- function()
{
z <- TRUE
while( z )
{
x <- readline( prompt="Enter an integer: " )
if ( x < 1 ) {
z <- FALSE
} else {
y <- factorial( as.numeric( x ) )
print( y )
}
}
}
myfun()
# Enter an integer: 1
# [1] 1
# Enter an integer: 5
# [1] 120
# Enter an integer: -1
# >
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.