|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
'来个VBA的
Option Explicit
Const PRECISION = 0.000001
Const COUNT_OF_NUMBER = 4 '4个数,可以更多或更少
Const NUMBER_TO_CAL = 24 '结果可以更小或更大
Dim number(COUNT_OF_NUMBER) As Double
Dim expression(COUNT_OF_NUMBER) As String
Function Search(n) As Boolean
Dim i As Integer, j As Integer
If n = 1 Then
Search = IIf((Abs(number(0) - NUMBER_TO_CAL) < PRECISION), True, False)
Exit Function
End If
For i = 0 To n - 1
For j = i + 1 To n - 1
Dim A As Double, B As Double
Dim expA As String, expB As String
A = number(i): B = number(j)
number(j) = number(n - 1)
expA = expression(i): expB = expression(j)
expression(j) = expression(n - 1)
expression(i) = "(" + expA + "+" + expB + ")"
number(i) = A + B
If (Search(n - 1)) Then Search = True: Exit Function
expression(i) = "(" + expA + "-" + expB + ")"
number(i) = A - B
If (Search(n - 1)) Then Search = True: Exit Function
expression(i) = "(" + expB + "-" + expA + ")"
number(i) = B - A
If (Search(n - 1)) Then Search = True: Exit Function
expression(i) = "(" + expA + "*" + expB + ")"
number(i) = A * B
If (Search(n - 1)) Then Search = True: Exit Function
If B <> 0 Then
expression(i) = "(" + expA + "/" + expB + ")"
number(i) = A / B
If (Search(n - 1)) Then Search = True: Exit Function:
End If
If A <> 0 Then
expression(i) = "(" + expB + "/" + expA + ")"
number(i) = B / A
If (Search(n - 1)) Then Search = True: Exit Function
End If
number(i) = A: number(j) = B
expression(i) = expA: expression(j) = expB
Next j, i
Search = False
End Function
Sub test()
Dim x As Integer, i As Integer
For i = 0 To COUNT_OF_NUMBER - 1
x = InputBox("输入第" & (i + 1) & "个数", COUNT_OF_NUMBER & "个数算" & NUMBER_TO_CAL)
number(i) = x
expression(i) = CStr(x)
Next
If Search(COUNT_OF_NUMBER) Then
MsgBox expression(0) & "=" & CStr(NUMBER_TO_CAL)
Else
MsgBox "无解"
End If
End Sub |
评分
-
1
查看全部评分
-
|