Fractions Demo

This demo allows the user to enter two fractions. These fractions are then added together and their reduced form is computed.

/ + /


Source Code:
<form action="fractions.asp" id=form1 name=form1>
<input type="text" name="num1" size="3" value="<%=Request("num1")%>" />/
<input type="text" name="den1" size="3" value="<%=Request("den1")%>" />+
<input type="text" name="num2" size="3" value="<%=Request("num2")%>" />/
<input type="text" name="den2" size="3" value="<%=Request("den2")%>" />

<input type="submit" / id=submit1 name=submit1>
</form>

<%
' The numerator and denominator of fraction 1 & 2 respectively
Dim iNumerator1, iDenominator1
Dim iNumerator2, iDenominator2

' The numerator and denominator of the resulting fraction
Dim iAnswerNumerator, iAnswerDenominator

' A variable for looping when finding the GCF
Dim I

' Read inputs - will throw errors if blank form is submitted
iNumerator1   = CInt(Request.QueryString("num1"))
iDenominator1 = Cint(Request.QueryString("den1"))
iNumerator2   = Cint(Request.QueryString("num2"))
iDenominator2 = Cint(Request.QueryString("den2"))


' Check for division by 0 problems
If iDenominator1 <> 0 And iDenominator2 <> 0 Then
	iAnswerNumerator   = (iNumerator1 * iDenominator2) + (iNumerator2 * iDenominator1)
	iAnswerDenominator = (iDenominator1 * iDenominator2)

	Response.Write "Unsimplified: "
	Response.Write iAnswerNumerator
	Response.Write "/"
	Response.Write iAnswerDenominator


	Response.Write "<br /><br />"

	' Simplify
	For I = iAnswerDenominator To 1 Step -1
		If iAnswerNumerator Mod I = 0 And iAnswerDenominator Mod I = 0 Then
			Exit For
		End If
	Next

	iAnswerNumerator = iAnswerNumerator / I
	iAnswerDenominator = iAnswerDenominator / I

	Response.Write "Simplified: "
	'If the denominator = 1 then there's no need to display it
	if iAnswerDenominator <> 1 then
		Response.Write iAnswerNumerator
		Response.Write "/"
		Response.Write iAnswerDenominator
	else
		'Since the denominator = 1, we can just display the numerator
		Response.Write iAnswerNumerator
	end if
	

	Response.Write "<br /><br />"

	' Check our work
	Response.Write "Check: " & (CSng(iNumerator1 / iDenominator1 + iNumerator2 / iDenominator2) = _
	                            CSng(iAnswerNumerator / iAnswerDenominator))
End If
%>


[Return to the Article]