Daffodil International University
IT Help Desk => Programming Language => Web based Developer Forum => Topic started by: msu_math on November 13, 2012, 10:52:09 AM
-
Unlike integers and floats, addition and subtraction of several fractions (rational number) require finding least common multiple (LCM) of the denominators of those fractions. Also, simplifying a fractions requires finding greatest common divisor (GCD) of both numerator and denominator of that fractions.
Here, we quote the PHP codes to determine the numerator and denominator of a fraction. Note that both of the following functions recall the function FracCheck() which is included in the previously posted related articles.
function FracNumer($A)
{
if(FracCheck($A)==0) { return NULL; }
else
{
$i=0;
$len=strlen($A)-1;
while($A[$i]!="/" && $i<=$len)
{
$Numer=$Numer.$A[$i];
$i++;
}
return $Numer;
}
}
function FracDenom($A)
{
if(FracCheck($A)==0) { return NULL; }
else
{
$i=0; $len=strlen($A)-1;
while($A[$i]!="/" && $i<=$len)
{
$i++;
}
if($i>$len) { return 1; }
else
{
$i++;
while($i<=$len)
{
$Denom=$Denom.$A[$i];
$i++;
}
return $Denom;
}
}
}
-
Sample Return Values:
FracNumer("-11/7"); Return value: "-11"
FracNumer("28"); Return value: "28"
FracDenom("28"); Return value: "1"
FracDenom("5/7"); Return value: "7"
FracNumer("-3/5/7"); Return value: NULL
*Because "-3/5/7" is not a valid fraction. ("-3/5/7" contains more than one "/")
FracDenom("51/7k"); Return value: NULL
*Because "51/7k" is not a valid fraction. ("51/7k" contains non-digit character "k")