以下回答参考 皆我百晓生、券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。
# Simple Desk Calculator
#
# This function takes an infix expression as input and returns its value.
# The expression should include parentheses, addition (+), subtraction (-),
# multiplication (*), division (/), and modulo (%) operations.
# It outputs the result or an error message if the expression is invalid.
simple_desk_calculator <- function(expr) {
# Function to evaluate the expression
evaluate_expression <- function(expression) {
tryCatch({
# Split the expression into tokens
tokens <- strsplit(expression, "")[[1]]
# Check for valid operators
if (length(tokens) < 3 || !all(token == "+" | "-" | "*" | "/" | "%")) {
return("ERROR IN INFIX NOTATION")
}
# Calculate the value based on precedence
left_operand <- parseNum(tokens[1])
operator <- tokens[2]
right_operand <- parseNum(tokens[3])
match(operator, c("+", "-", "*", "/", "%"))
# Evaluate the expression recursively
eval(left_operand, right_operand)
}, error = function(e) {
return(e$message)
})
}
# Split the input expression into tokens
tokens <- strsplit(expr, "")[[1]]
# Try evaluating the expression
tryCatch({
evaluate_expression(expr)
}, error = function(e) {
return(e$message)
})
}
# Example usage:
# exprs <- c("(3*5*(4*8)%2)", "1+2(", "2/0", "2.5%2", "2%2.5")
# results <- lapply(exprs, simple_desk_calculator)
# print(results)
This code defines a simple_desk_calculator
function that evaluates an infix expression using recursion and tokenization. The function first checks if the expression is valid by ensuring it has three tokens and uses only allowed operators. Then, it calculates the value of the expression according to the order of operations. If the expression is not valid, it returns an error message. Finally, we demonstrate how to use this function with example expressions and print their results.