因为作业繁重,特写此来写作业,不过只能进行简单运算,暂不支持带有括号,常量尽量简单些
用的是公式法解方程,自动搜索简单的a,b,c带入公式法运算,得出结果
Option Explicit
Private Type Item '项
ItemString As String '项的字符串 永远为正数
Symbol As Long '符号(1=+ -1=- 2=* -2=/)
Time As Long '项的次数
Coefficient As Single '项的系数
Unknown As String '未知数字符
ConstItem As Boolean '是否为常数项(True是 False否)
Position As Boolean '位置是左(False)还是右(True)
End Type
'公式法
'x=(-b±根号(b^2-4ac))/2a
Public Function Solving_Quadratics(ByVal Quadratics As String, ByRef x1 As Single, ByRef x2 As Single) As Long '解一元二次方程
On Error Resume Next
'一元二次方程式字符串 解1 解2
'返回值: 0=无解 1=有两个相同的实数根 2=有两个不相同的实数根
Dim QuaItem() As Item '方程式的项
Dim LeftItem() As Item '左边的项
Dim RightItem() As Item '右边的项
Dim QuaItemCount As Long '方程式的项数
Dim LeftItemCount As Long
Dim RightItemCount As Long
Dim LeftOrRight As Boolean '是方程左边False还是右边True
LeftOrRight = False '首先遍历左边
'-------------------------------------------------------------------------------------方程式正误检测Begin
If (Quadratics = "") Then '要解的方程式为空
Solving_Quadratics = 0
Exit Function
End If
'-------------------------------------------------------------------------------------方程式正误检测End
'-------------------------------------------------------------------------------------去括号Begin
'根据去括号法则,前面是-里面所有的项都要变号(+变- -变+) 前面是*就用乘法分配律 前面是/
'-------------------------------------------------------------------------------------去括号End
'-------------------------------------------------------------------------------------获取每一项存入Begin
'+-为一项
Dim i As Long
Dim Char As String
Dim LastSymbolPlace As Long '上一个符号(+-)位置
LastSymbolPlace = 1 '第一个自成一项
For i = 0 To Len(Quadratics) - 1 '遍历每一个字符
Char = Mid(Quadratics, i + 1, 1) '取出这个字符
If (Char = "+") Or (Char = "-") Or (Char = "=") Then '成一项
ReDim Preserve QuaItem(QuaItemCount)
QuaItem(QuaItemCount).ItemString = Mid(Quadratics, LastSymbolPlace, i + 1 - LastSymbolPlace)
'判断这一项的符号
Select Case Mid(Quadratics, LastSymbolPlace, 1)
Case "+"
QuaItem(QuaItemCount).Symbol = 1
QuaItem(QuaItemCount).ItemString = Right(QuaItem(QuaItemCount).ItemString, Len(QuaItem(QuaItemCount).ItemString) - 1) '去掉项的符号
Case "-"
QuaItem(QuaItemCount).Symbol = -1
QuaItem(QuaItemCount).ItemString = Right(QuaItem(QuaItemCount).ItemString, Len(QuaItem(QuaItemCount).ItemString) - 1)
Case "*"
QuaItem(QuaItemCount).Symbol = 2
QuaItem(QuaItemCount).ItemString = Right(QuaItem(QuaItemCount).ItemString, Len(QuaItem(QuaItemCount).ItemString) - 1)
Case "/"
QuaItem(QuaItemCount).Symbol = -2
QuaItem(QuaItemCount).ItemString = Right(QuaItem(QuaItemCount).ItemString, Len(QuaItem(QuaItemCount).ItemString) - 1)
Case Else '都不是就默认是+ And +号可以省略
QuaItem(QuaItemCount).Symbol = 1
End Select
'获取这个项的次数
Dim TimePlace As Long '次数在这个项中的开始位置
TimePlace = InStr(1, QuaItem(QuaItemCount).ItemString, "^", vbTextCompare) '获取^的位置
If (TimePlace = 0) Then '没有找到^则说明默认是一次项
QuaItem(QuaItemCount).Time = 1 '一次项
Else '有^ 说明不是一次项 就获取次数
QuaItem(QuaItemCount).Time = Mid(QuaItem(QuaItemCount).ItemString, TimePlace + 1, L