我编写了一个使用Maclaurin系列来计算sin(x)的程序,但是当我尝试调试它时,它会产生溢出错误。这是代码,任何人都可以帮助我吗?
Public Class Form1
Private Function sin(ByVal x As Double) As Double
Dim sinx, radx, abc As Double
sinx = 0
radx = x * Math.PI / 180
For i = 1 To 20 Step 2
abc = (Math.Pow(-1, (i / 2)) * Math.Pow(radx, i)) / factorial(i)
sinx += abc
Next
Return sinx
End Function
Private Function factorial(ByVal n As Integer) As Integer
If (n = 0) Or (n = 1) Then
Return 1
Else
Return n * factorial(n - 1)
End If
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub BtnCalc_Click(sender As Object, e As EventArgs) Handles BtnCalc.Click
Dim x As Integer
x = Val(TxtInput.Text)
TxtAns.Text = sin(x)
End Sub
End Class
答案 0 :(得分:0)
下面的代码给出了使用Maclaurin系列
的角度正弦的答案对于您的界面,您需要2个标签,2个文本框和3个按钮
Public Class Maclaurin_series
Private Function sin(ByVal x As Double) As Double
Dim sinx, radx, abc As Double
sinx = 0
radx = x * Math.PI / 180
For i = 1 To 20 Step 2
abc = (Math.Pow(-1, (i \ 2)) * Math.Pow(radx, i)) / factorial(i)
sinx += abc
Next
Return sinx
End Function
Private Function factorial(ByVal n As Integer) As Long
If (n = 0) Or (n = 1) Then
Return 1
Else
Return n * factorial(n - 1)
End If
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub BtnCalc_Click(sender As Object, e As EventArgs) Handles BtnCalc.Click
Dim x As Integer
x = Val(TxtInput.Text)
TxtAns.Text = sin(x)
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles BtnExit.Click
Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TxtAns.Text = ""
TxtInput.Text = " "
End Sub
结束班
答案 1 :(得分:0)
Sub testDBLCOS() Debug.Print "VBA COS", Cos(0.25 * Pi) Debug.Print "TAYLOR", DBLCOS(0.25 * Pi), "DELTA", DBLCOS(0.25 * Pi) - Cos(0.25 * Pi) End Sub
Sub testDBLSIN() Debug.Print "VBA SIN", sin(0.25 * Pi) Debug.Print "TAYLOR", DBLSIN(0.25 * Pi), "DELTA", DBLSIN(0.25 * Pi) - sin(0.25 * Pi) End Sub
Function DBLCOS(x, Optional ITER As Long = 10) As Double Dim P, k, x2, d, f, c As Double f = 2 c = 2 k = 1 x2 = x * x SUM = 1 P = 1 For I = 1 To ITER k = -k P = P * x2 SUM = SUM + k * P / f c = c + 1 f = f * c c = c + 1 f = f * c Next DBLCOS = SUM End Function Function DBLSIN(x, Optional ITER As Long = 10) As Double Dim P, k, x2, d, f, c As Double k = 1 c = 3 f = 6 P = x x2 = x * x SUM = x For I = 1 To ITER k = -k P = P * x2 SUM = SUM + k * P / f c = c + 1 f = f * c c = c + 1 f = f * c Next DBLSIN = SUM End Function