Reputation: 41
I am actually new here. I would like to create a simple calculator in R Programming with combination of readline() function and different functions Here is my current code:
add <- function(x, y) {
return(x + y)
}
subtract <- function(x, y) {
return(x - y)
}
multiply <- function(x, y) {
return(x * y)
}
divide <- function(x, y) {
return(x / y)
}
factors <- function(x) {
if(choice <=5){
choice <- readline(prompt="Enter the number: ")
print(paste("The factors of",x,"are:"))
for(i in 1:x) {
if((x %% i) == 0) {
print(i)
}
}}
}
print("******Simple R Calculator - Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Factors")
print("6.Prime")
choice = as.integer(readline(prompt="Enter choice[1/2/3/4/5/6]: "))
num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2), divide(num1, num2), factors(i))
print(paste(num1, operator, num2, "=", result))
When I run this function, it asks to enter the first number and second number to get the results. But for "choice" number 5 and 6, I do not want to have first number and second number popped up instead only requires one number. Please help me guys and clarify if I may not quite clear on my question. I appreciate your help.
Upvotes: 1
Views: 3779
Reputation: 350
It sounds like a basic if statement is what you are looking for. If I am understanding the question right, if choice is 5 or 6 you don't want to prompt for 2 numbers. Try this:
if (choice == 5 | choice == 6) {
num1 = as.integer(readline(prompt="Enter number: "))
} else {
num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))
}
Upvotes: 2