Like integers and floats, variable to process fractions(rational numbers) can’t be declared directly in the programming languages. But in many programming cases, rational input-output becomes a matter of interest. Here we show that rational input-output can be processed by using string variable in an easier way.
A number x is said to be a rational number if there exists integer p and nonzero integer q such that x = p/q. Then p is called the numerator of x and q is called the denominator of x. Since any integer m equals m/1, integers can be considered as rational numbers with denominator 1. A string of digits consisting of only a single “/” at an interior position can be considered as a rational number with numerator, the integer formed by the digits preceding the slash and denominator, the integer formed by the digits following the slash.
Before we start any basic operation with strings representing rational inputs, it is prerequisites that we check whether a string represents a valid rational number or not. By a valid rational number we mean a string of digits containing exactly one “/” at an interior position.
The following function (PHP code) test whether the string $A represents a valid rational number or not.
function FracCheck($A)
{
$i=0;
$len=strlen($A)-1;
$CheckSlash=0;
if($A[0]=="/" || $A[$len]=="/" || ($A[0]=="-" && $A[1]==NULL))
return 0;
while($i<=$len)
{
if(is_numeric($A[$i]) || $A[$i]=="/" || $A[$i]=="-")
{
if($i>0 && $A[$i]=="-" && !($A[$i-1]=="/"))
return 0;
if($A[$i]=="/")
$CheckSlash++;
}
else
return 0;
$i++;
}
if($CheckSlash<=1)
return 1;
else
return 0;
}