R 程序创建一个简单的计算器


2023年2月5日, Learn eTutorial
4641

在此,我们将解释如何编写一个 R 程序来创建一个简单的计算器。

什么是计算器?

一个简单的计算器是用于执行简单数学运算的设备,例如

  • 加法
  • 减法
  • 乘法
  • 除法。

因此,要制作一个计算器,我们需要一个选择操作并执行所选操作以获得结果的选项。

如何在 R 程序中实现一个简单的计算器?

在这个 R 程序中,我们从用户那里获取操作选择和两个数字,分别存储在变量 **n1、n2 和 choice** 中。然后根据 **choice** 调用相应的用户定义函数。这里我们使用 `switch` 分支来执行特定的函数。选择操作符 **'+'、'-'、'*'** 和 **'/'** 分别对应用户的选择 1、2、3、4。

算法

步骤 1:向用户显示适当的消息

步骤 2:使用 readline() 将用户输入存储到变量 **n1、n2、choice** 中

步骤 3:定义加法、减法、乘法和除法的用户定义函数

步骤 4:提供 `switch` 选项

步骤 5:根据 **choice** 调用相应的函数

步骤 6:打印结果

R 源代码

                                          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)
}
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = as.integer(readline(prompt="Enter choice[1/2/3/4]: "))
n1 = as.integer(readline(prompt="Enter first number: "))
n2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(n1, n2), subtract(n1, n2), multiply(n1, n2), divide(n1, n2))
print(paste(n1, operator, n2, "=", result))
                                      

输出

[1] "Select operation."
[1] "1.Add"
[1] "2.Subtract"
[1] "3.Multiply"
[1] "4.Divide"
Enter choice[1/2/3/4]: 4
Enter first number: 40
Enter second number: 2
[1] "40/ 2 = 20"