Home > front end >  Error message for dividing by zero when variable in 0 is = 1
Error message for dividing by zero when variable in 0 is = 1

Time:10-16

The program keep saying that there is a division by zero in Term = (-1 ^ (i - 1)) * (X ^ (2 * (i - 1))) / M even though M was set to equal 1 before this calculation took place. I have tried change the value of M but it continuously keeps giving the division by 0 error message. This program is supposed to calculate sin(x) without using the built in function. Any insight towards this is very much appriciated.

Option Explicit
Sub MainPrg()
Dim X As Single, LastTerm As Long, M As Double, Term As Long, i As 
Single, _
 ActVal As Single, Sum As Long
'
'
X = InputBox("Please input the angle in degrees")
    X = X * (3.14159 / 180)
LastTerm = InputBox("Please enter the largest value for the last 
term in the series")
    ActVal = Sin(X)
Call SinCalc(LastTerm, M, i, Term, Sum, X)

MsgBox ("The calculated value is " & Sum & " And the actual value 
is " & ActVal)
End Sub

Function Fact(ByVal i As Single, ByRef M As Double)

    M = M * (2 * (i - 1))
End Function

Sub SinCalc(ByVal LastTerm As Double, ByVal M As Double, ByVal i As 
Single, _
    ByRef Term As Long, ByRef Sum As Long, ByVal X As Single)
i = 1
M = 1
Sum = 0
Do
    Term = (-1 ^ (i - 1)) * (X ^ (2 * (i - 1))) / M
    Sum = Sum   Term
If (Abs(Term) < LastTerm) Then Exit Do
    i = i   1
    Call Fact (i,M)
Loop
End Sub

CodePudding user response:

Your line with the issue Term = (-1 ^ (i - 1)) * (X ^ (2 * (i - 1))) / M is inside a loop so even if at the beginning M is equal to 1 it can become equal to 0 after (this happens during the fact function)

  • Related