给出了以下问题:https://imgur.com/a/2OpPKfW
编写一个函数polyPrint,该函数可以很好地打印方程式(1)的多项式。例如, 如果a对应于向量c(2,0,1,-2,5),则应该使用polyPrint(a)打印:
2 + x ^ 2 +(-2)* x ^ 3 + 5 * x ^ 4
请注意polyPrint应该如何处理a的元素为0、1或负数的情况!
此刻,我正在使用循环和猫。那太难了,因为我需要用ifelse语句为1,0以及任何负数做很多事。
我还有其他功能可以用来简化此过程吗?
# Regular function
polyFunction <- function(x,a){
n <- seq(1,length(a))
sum(ax^(n-1))
}
# Printing the calculation method
a <- c(2,1,-2,5)
polyPrint <- function(a){
n <- seq(1,length(a))
for(i in n){
result <- c()
result <- c(result,cat(a[i],'x^',1+i,'+ '))
}
}
polyPrint(a)
预期输出是具有以下格式的多项式函数:
p(x)= a0 + a1x + a2x ^ 2 + ... + anxn
此刻,我得到2 * x ^ 2 + 0 * x ^ 3 +1 * x ^ 4 + -2 * x ^ 5 + 5 * x ^ 6 +
具有向量c(2,0,1,-2,5)