简化分数程序不适用于所有情况

时间:2018-07-27 00:13:32

标签: actionscript-3 if-statement fractions

我正在使用动作脚本编写分数简化程序。该代码适用于大多数情况,但不适用于分子和分母为负的分数。假设当正确答案为5/1时,如果用户输入-25 / -5,则输出-5 / -1。同样,当用户输入带有负分子和分母的分数时,分母为-1时,程序将输出带有减少的答案旁边的两个负数。请指教。谢谢!

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;

}

1 个答案:

答案 0 :(得分:0)

将此条件设为要在reduceFraction()函数中检查的第一个条件

if (denominator < 0) {
    denominator *= -1;
    numerator *= -1;
}

问题将得到解决。