gpt4 book ai didi

vba - 如何对单元格值进行三重解析以形成多项式表达式?

转载 作者:行者123 更新时间:2023-12-04 21:02:58 25 4
gpt4 key购买 nike

编辑:下面发布的大多数修改后的代码。

编辑:我希望让用户输入多项式,例如: A(n) * X^n + A(n-1)*X^(n-1) + A(n-2)*X^(n-2 ) + ... + A(0)

我正在使用 Excel 宏来演示中间值定理。用户在 A2 中输入度数,在 B2 中输入系数。

目前 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

最佳答案

您需要围绕您已经编写的内容构建一个循环,然后连接 Coefficient & "x^" & DegreeString 内多变的。它可能看起来像这样:

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用于检查对象是否为空;简单数据类型用 "" 初始化对于 String0对于数字,因此永远不会触发 isNull .

关于vba - 如何对单元格值进行三重解析以形成多项式表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com