I'm doing a fraction calculator and I'm trying to add 2 fractions when I put in my fractions it just adds my Whole numbers only and nothing else if my fraction is 2 3/4 + 2 3/5 it add the whole numbers and outputs 4

    var firstStep = firstDenomInTextField! * firstWholeInTextField! / firstDenomInTextField!

    var secondStep = firstStep + firstNumInTextField! / firstDenomInTextField!

    var thirdStep = secondDenomInTextField! * secondWholeInTextField! / secondDenomInTextField!
    var fourthStep = thirdStep + secondNumInTextField! / secondDenomInTextField!

    var calculatedAnswer = (secondStep + fourthStep)
    var numerator = Int(calculatedAnswer * 10 * 10)
    println(numerator)
    answerLabel.hidden = false
    answerLabel.text = printSimplifiedFraction(Numerator: numerator)

printSimplifiedFraction Function

func printSimplifiedFraction(Numerator numerator: Int, Denominator denominator: Int = 100) -> String
{
    var finalNumerator = numerator;
    var finalDenominator = denominator;

    var wholeNumbers:Int = numerator / denominator;
    var remainder:Int = numerator % denominator;

    //println("wholeNumbers = \(wholeNumbers), remainder = \(remainder)");
    //println("\(denominator) % \(remainder) = \(denominator % remainder)");

    if(remainder > 0)
    {
        // see if we can simply the fraction part as well
        if(denominator % remainder == 0) // no remainder means remainder can be simplified further
        {
            finalDenominator = denominator / remainder;
            finalNumerator = remainder / remainder;
        }
        else
        {
            finalNumerator = remainder;
            finalDenominator = denominator;
        }
    }

    if(wholeNumbers > 0 && remainder > 0)
    {
        // prints out whole number and fraction parts
        return("Simplified fraction of \(numerator)/\(denominator) = \(wholeNumbers) \(finalNumerator)/\(finalDenominator)");
    }
    else if (wholeNumbers > 0 && remainder == 0)
    {
        // prints out whole number only
        return("Simplified fraction of \(numerator)/\(denominator) = \(wholeNumbers)");
    }
    else
    {
        // prints out fraction part only
        return("Simplified fraction of \(numerator)/\(denominator) = \(finalNumerator)/\(finalDenominator)");
    }
}

If you need any clarifications or questions please comment them down below

Related posts

Recent Viewed