jeudi 26 juillet 2018

Simplify fractions program does not work for all cases

I am coding a fraction simplifier using actionscript. The code works for most cases however, not for fractions that have a negative numerator and denominator. Say if the user inputs -25/-5, it outputs -5/-1, when the correct answer is 5/1. Also, when the user inputs a fraction with a negative numerator and denominator, however, the denominator being -1, the program outputs with two negatives beside the reduced answer. Please advise. Thanks!

btnReduce.addEventListener(MouseEvent.CLICK, reduceFraction);
function reduceFraction(e:MouseEvent):void
{  
    var numerator:int;      // the numerator of the fraction
    var denominator:int     // the denominator of the fraction
    var gcd:int;            // the greatest common divisor of the numerator and denominator


    numerator = int(txtinNumerator.text);
    denominator = int(txtinDenominator.text);

    if (denominator == 0) {
        lblOutput.text = "The denominator cannot be 0.";
    }
    else {
        gcd = findGCD(numerator, denominator);
        lblOutput.text = numerator.toString() + "/" + denominator.toString() + " can be reduced to " + (numerator/gcd).toFixed(0) + "/" + (denominator/gcd).toFixed(0);
    }

    if (numerator == 0){
        lblOutput.text = numerator.toString() + "/" + denominator.toString() + " can be reduced to 0 ";
    }

    if (denominator == 1){
        lblOutput.text = numerator.toString() + "/" + denominator.toString() + " can be reduced to " + numerator.toString();
    }

    if (denominator == -1){
        lblOutput.text = numerator.toString() + "/" + denominator.toString() + " can be reduced to " + "-" + numerator.toString();
    }
    if (numerator == denominator){
        lblOutput.text = numerator.toString() + "/" + denominator.toString() + " can be reduced to " + "1";
    }


}


function findGCD(n1:int,n2:int):int
{
    var divisor:int;    // the divisor



    if (n1 < n2){
        for (divisor = Math.abs(n1); divisor > 1; divisor--){
            if (n1 % divisor == 0 && n2 % divisor == 0){
                return divisor;
            }
        }
    }
    else{
        for (divisor = Math.abs(n2); divisor > 1; divisor--){
            if (n1 % divisor == 0 && n2 % divisor == 0){
                return divisor;
            }
        }
    }
    return 1;

}

Aucun commentaire:

Enregistrer un commentaire