编辑:大部分修订后的代码发布在下面。
编辑:我希望让用户输入多项式,例如:A(n)* X ^ n + A(n-1)* X ^(n-1)+ A(n-2)* X ^( n-2)+ ... + A(0)
我正在使用Excel宏来演示中间值定理。用户输入A2中的Degree,B2中的Coefficient。
目前,MsgBox可以以Coefficient * x ^ Degree的形式返回一阶多项式。我希望MsgBox能够返回更复杂的多项式,以便用户可以确认输入了正确的多项式。
这是代码:
Sub Function1()
MsgBox "Enter polynomial by terms."
counter = 1
counter = counter + 1
Degree = Cells(counter, 1).Value 'A2
Coefficient = Cells(counter, 2).Value 'B2
' If cell value is null stop
If IsNull(Degree) = True Then
MsgBox "IsNull(Degree)=True"
End If
If IsNull(Coefficient) Then
MsgBox "IsNull(Coefficient)=True"
End If
If IsNumeric(Len(Trim(Degree))) = True And IsNumeric(Len(Trim(Coefficient))) Then
MsgBox "Degree is numeric"
If Degree Mod 1 = 0 Then
MsgBox "Degree is integer"
End If
End If
MsgBox Coefficient & "x^" & Degree
' How repeat this process to show in MsgBox entire polynomial?
End Sub
编辑:修订后的代码:
Option Explicit
Sub Function1()
Dim Polynomial As String
Dim Sign
Dim counter As Integer
Dim Degree
Dim Coefficient
While Cells(counter + 1, 1).Value <> "" And Cells(counter + 1, 2).Value <> "" '+1 because top row occupied by column A, column B titles. If cell is empty stop.
MsgBox "Enter polynomial by terms."
Degree = Cells(counter + 1, 1).Value 'A2
Coefficient = Cells(counter + 1, 2).Value 'B2
If (Coefficient < 0) Then Sign = " - " ' if coefficient negative
Else: If Coefficient > 0 Then Sign = " + " ' if coefficient positive
End If
Polynomial = Polynomial & " " & Coefficient & "x^" & Degree 'concatenation string, list polynomial.
counter = 1
counter = counter + 1
Wend
MsgBox poly
End Sub
答案 0 :(得分:1)
您需要围绕已编写的内容构建一个循环,并在Coefficient & "x^" & Degree
变量内汇总String
。它看起来像这样:
Dim poly as String
Dim sign as String
' Iterate over data cells:
while Cells(counter,1).Value <> ""
' What you're already doing...
' ...plus:
IIf(Coefficient < 0, sign = " - ", sign = " + ")
' String concatenation:
poly = poly & " " & Coefficient & "x^" & Degree
counter=counter+1
Wend
' Finally:
Msgbox poly
编辑:此外,如果要检查空值,请使用If Cells(counter,1).value = "" Then ...
。 IsNull
用于检查对象是否为空;简单数据类型初始化为""
String
和0
数字,因此永远不会触发isNull
。