如何将小数转换为分数 - Swift

时间:2014-10-16 04:19:00

标签: ios swift

我有一个分数计算器,当我计算它时,它会变成十进制。我想把它变成分数。我不知道如何在代码中执行此操作,但我尝试将计算分开,但在此处不起作用的是代码以及我的故事板的屏幕截图 https://www.dropbox.com/s/fmapxaou49zap05/iOS%20Simulator%20Screen%20Shot%20Oct%2015%2C%202014%2C%209.37.43%20PM.png?dl=0 < / p>

        //Adding Function
        changingSignsLabel.text = "+"
        let firstDenomInTextField:Double! = (firstDenominatorTextField.text as NSString).doubleValue
        let firstNumInTextField:Double! = (firstNumeratorTextField.text as NSString).doubleValue
        let firstWholeInTextField:Double! = (firstWholeNumberTextField.text as NSString).doubleValue

        let secondDenomInTextField:Double! = (secondDenominatorTextField.text as NSString).doubleValue
        let secondNumInTextField:Double! = (secondNumeratorTextField.text as NSString).doubleValue
        let secondWholeInTextField:Double! = (secondWholeNumberTextField.text as NSString).doubleValue

        var firstStep = firstDenomInTextField! * firstWholeInTextField! / firstDenomInTextField!

        var secondStep = firstStep + firstNumInTextField! / firstDenomInTextField!

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

        var calculatedAnswer = (secondStep + fourthStep)

        answerLabel.hidden = false

        answerLabel.text = "\(calculatedAnswer)"

如果您有任何问题或疑虑,请在下面发表评论

感谢您的帮助

3 个答案:

答案 0 :(得分:6)

为了让它每次都能工作,你想使用Euclidian算法,它在swift中看起来像这样:

func simplify(top:Int, bottom:Int) -> (newTop:Int, newBottom:Int) {

    var x = top
    var y = bottom
    while (y != 0) {
        var buffer = y
        y = x % y
        x = buffer
    }
    var hcfVal = x
    var newTopVal = top/hcfVal
    var newBottomVal = bottom/hcfVal
    return(newTopVal, newBottomVal)
}

您应该只能将其添加到您的程序中,然后使用以下命令进行调用:

simplify(5,10)

...返回1和2.希望这有助于其他人试图找到这个问题的简单答案。

答案 1 :(得分:2)

更新答案

我给你写了一个演示应用程序:

Demo App Screenshot

Swift源代码:

将它放在视图控制器中。

var numeratorField:UITextField?;
var denominatorField:UITextField?;
var equalButton:UIButton?;
var wholeNumberLabel:UILabel?;
var numeratorLabel:UILabel?;
var denominatorLabel:UILabel?;
var dividerLine:UIView?;

var appName:UILabel?;
var instructions:UILabel?;


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    initViews();
    initConstraints();
}

// ---------------------------------------------------------------------
// MARK: Interface Setup
// ---------------------------------------------------------------------

func initViews()
{
    self.numeratorField = UITextField();
    self.numeratorField?.layer.cornerRadius = 5.0;
    self.numeratorField?.layer.borderWidth = 1.0;
    self.numeratorField?.textAlignment = NSTextAlignment.Center;

    self.denominatorField = UITextField();
    self.denominatorField?.layer.cornerRadius = 5.0;
    self.denominatorField?.layer.borderWidth = 1.0;
    self.denominatorField?.textAlignment = NSTextAlignment.Center;

    self.equalButton = UIButton();
    self.equalButton?.setTitle("=", forState: UIControlState.Normal);
    self.equalButton?.addTarget(self, action: "calculateAnswer", forControlEvents: UIControlEvents.TouchUpInside);
    self.equalButton?.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal);
    self.equalButton?.layer.cornerRadius = 5.0;
    self.equalButton?.backgroundColor = UIColor.lightGrayColor();

    self.wholeNumberLabel = UILabel();
    self.wholeNumberLabel?.textAlignment = NSTextAlignment.Right;
    self.wholeNumberLabel?.font = UIFont(name: "HelveticaNeue", size: 20);

    self.numeratorLabel = UILabel();
    self.numeratorLabel?.textAlignment = NSTextAlignment.Center;
    self.numeratorLabel?.font = UIFont(name: "HelveticaNeue", size: 14);

    self.denominatorLabel = UILabel();
    self.denominatorLabel?.textAlignment = NSTextAlignment.Center;
    self.denominatorLabel?.font = UIFont(name: "HelveticaNeue", size: 14);

    self.dividerLine = UIView();
    self.dividerLine?.backgroundColor = self.numeratorLabel!.textColor;
    self.dividerLine?.alpha = 0;

    self.appName = UILabel();
    self.appName?.text = "Fraction App";
    self.appName?.font = UIFont(name: "HelveticaNeue-Bold", size: 24);
    self.appName?.textAlignment = NSTextAlignment.Center;

    self.instructions = UILabel();
    self.instructions?.textAlignment = NSTextAlignment.Center;
    self.instructions?.text = "Enter a value in the numerator and denominator field, then press the equal sign to see the answer";
    self.instructions?.numberOfLines = 0;
    self.instructions?.lineBreakMode = NSLineBreakMode.ByWordWrapping;

    self.view.addSubview(self.numeratorField!);
    self.view.addSubview(self.denominatorField!);
    self.view.addSubview(self.equalButton!);
    self.view.addSubview(self.wholeNumberLabel!);
    self.view.addSubview(self.numeratorLabel!);
    self.view.addSubview(self.denominatorLabel!);
    self.view.addSubview(self.dividerLine!);
    self.view.addSubview(self.appName!);
    self.view.addSubview(self.instructions!);
}

func initConstraints()
{
    self.appName?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.numeratorField?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.denominatorField?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.equalButton?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.wholeNumberLabel?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.numeratorLabel?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.denominatorLabel?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.dividerLine?.setTranslatesAutoresizingMaskIntoConstraints(false);
    self.instructions?.setTranslatesAutoresizingMaskIntoConstraints(false);

    var views:NSMutableDictionary = NSMutableDictionary();
    views.setValue(self.appName, forKey: "appName");
    views.setValue(self.numeratorField, forKey: "numeratorField");
    views.setValue(self.denominatorField, forKey: "denominatorField");
    views.setValue(self.equalButton, forKey: "equalButton");
    views.setValue(self.wholeNumberLabel, forKey: "wholeNumberLabel")
    views.setValue(self.numeratorLabel, forKey: "numeratorLabel");
    views.setValue(self.denominatorLabel, forKey: "denominatorLabel");
    views.setValue(self.dividerLine, forKey: "dividerLine");
    views.setValue(self.instructions, forKey: "instructions");

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[appName]|", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-50-[appName]", options: nil, metrics: nil, views: views));

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[instructions]-20-|", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[instructions]-100-|", options: nil, metrics: nil, views: views));

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-35-[numeratorField(75)]-10-[denominatorField(==numeratorField)]-10-[equalButton]-10-[wholeNumberLabel(>=20)]-2-[dividerLine(15)]", options: nil, metrics: nil, views: views));

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[numeratorField(50)]", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[denominatorField(==numeratorField)]", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[equalButton(==numeratorField)]", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[wholeNumberLabel(==numeratorField)]", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[numeratorLabel]", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[denominatorLabel]", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[dividerLine(1)]", options: nil, metrics: nil, views: views));

    self.view.addConstraint(NSLayoutConstraint(item: self.numeratorLabel!, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.wholeNumberLabel, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0.0));
    self.view.addConstraint(NSLayoutConstraint(item: self.denominatorLabel!, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.wholeNumberLabel, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0.0));

    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[numeratorLabel(==wholeNumberLabel)]", options: nil, metrics: nil, views: views));
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[denominatorLabel(==wholeNumberLabel)]", options: nil, metrics: nil, views: views));



    self.view.addConstraint(NSLayoutConstraint(item: self.numeratorField!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));
    self.view.addConstraint(NSLayoutConstraint(item: self.denominatorField!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));
    self.view.addConstraint(NSLayoutConstraint(item: self.equalButton!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));
    self.view.addConstraint(NSLayoutConstraint(item: self.wholeNumberLabel!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));
    self.view.addConstraint(NSLayoutConstraint(item: self.dividerLine!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));

    self.view.addConstraint(NSLayoutConstraint(item: self.numeratorLabel!, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.wholeNumberLabel, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));
    self.view.addConstraint(NSLayoutConstraint(item: self.denominatorLabel!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.wholeNumberLabel, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0));
}

func getLowestCommonDenominator(Numerator numerator:Int, Denominator denominator:Int) -> Int
{
    var finalDenominator = denominator;

    //println("\(numerator) / \(finalDenominator) = \(numerator % finalDenominator)");

    if(numerator % 2 == 0 && finalDenominator % 2 == 0) // even number
    {
        return self.getLowestCommonDenominator(Numerator: numerator / 2.0, Denominator: finalDenominator / 2.0);
    }
    else if(numerator % 3 == 0 && finalDenominator % 3 == 0) // odd number
    {
        return self.getLowestCommonDenominator(Numerator: numerator / 3.0, Denominator: finalDenominator / 3.0);
    }
    else // prime number, always have a remainder
    {
        //println("lowest common denominator = \(finalDenominator)");

        return finalDenominator;
    }
}

func calculateAnswer()
{
    // prevent division by zero
    if(self.denominatorField?.text == "0")
    {
        var alert:UIAlertView = UIAlertView(title: "Division By Zero", message: "Divide by zero yields undefined value", delegate: self, cancelButtonTitle: "OK");
        alert.show();

        return;
    }

    // clear previous values;
    self.wholeNumberLabel?.text = "";
    self.numeratorLabel?.text = "";
    self.denominatorLabel?.text = "";

    var numeratorString:NSString = self.numeratorField!.text;
    var denominatorString:NSString = self.denominatorField!.text;

    if (numeratorString.length == 0 || denominatorString.length == 0)
    {
        //var alert:UIAlertView = UIAlertView(title: "Input Missing", message: "Enter a value for numerator and denominator then press the equal sign to get the answer", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: nil, nil);

        var alert:UIAlertView = UIAlertView(title: "Input Missing", message: "Enter a value for numerator and denominator then press the equal sign to get the answer", delegate: nil, cancelButtonTitle: "OK");

        alert.show();
    }
    else
    {
        var shouldShowWholeParts:Bool = false;
        var shouldShowFractionParts:Bool = false;

        var numerator:Int = self.numeratorField!.text.toInt()!;
        var denominator:Int = self.denominatorField!.text.toInt()!;

        var finalNumerator = numerator;
        var finalDenominator = self.getLowestCommonDenominator(Numerator: numerator, Denominator: denominator);

        if(finalDenominator < denominator)
        {
            denominator = finalDenominator;
            numerator = numerator / finalDenominator;
        }

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

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

        if(wholeNumbers != 0)
        {
            shouldShowWholeParts = true;
        }
        else
        {
            shouldShowWholeParts = false;
        }

        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;
            }

            shouldShowFractionParts = true;
        }
        else
        {
            shouldShowFractionParts = false;
        }

        var answer:NSString?;

        if(wholeNumbers > 0 && remainder > 0)
        {
            answer = NSString(format: "\(wholeNumbers) \(finalNumerator)/\(finalDenominator)");

            // prints out whole number and fraction parts
            //println("Simplified fraction of \(numerator)/\(denominator) = \(wholeNumbers) \(finalNumerator)/\(finalDenominator)");
        }
        else if (wholeNumbers > 0 && remainder == 0)
        {
            answer = NSString(format: "\(wholeNumbers)");

            // prints out whole number only
            //println("Simplified fraction of \(numerator)/\(denominator) = \(wholeNumbers)");
        }
        else
        {
            answer = NSString(format: "\(finalNumerator)/\(finalDenominator)");

            // prints out fraction part only
            //println("Simplified fraction of \(numerator)/\(denominator) = \(finalNumerator)/\(finalDenominator)");
        }

        if(shouldShowWholeParts)
        {
            self.wholeNumberLabel?.text = NSString(format: "\(wholeNumbers)");
        }

        if(shouldShowFractionParts)
        {
            self.numeratorLabel?.text = NSString(format: "\(finalNumerator)");
            self.denominatorLabel?.text = NSString(format: "\(finalDenominator)");
            self.dividerLine?.alpha = 1;
        }
        else
        {
            self.dividerLine?.alpha = 0;
        }


    }
}

原始答案

这是你要找的吗?

结果:

Simplified fraction of 7/8 = 7/8
Simplified fraction of 12/8 = 1 1/2
Simplified fraction of 5/16 = 5/16
Simplified fraction of 342/23 = 14 20/23
Simplified fraction of 129/72 = 1 57/72

源代码:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    printSimplifiedFraction(Numerator: 7, Denominator: 8);
    printSimplifiedFraction(Numerator: 12, Denominator: 8);
    printSimplifiedFraction(Numerator: 5, Denominator: 16);
    printSimplifiedFraction(Numerator: 342, Denominator: 23);
    printSimplifiedFraction(Numerator: 129, Denominator: 72);
}

func printSimplifiedFraction(Numerator numerator: Int, Denominator denominator:Int)
{
    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
        println("Simplified fraction of \(numerator)/\(denominator) = \(wholeNumbers) \(finalNumerator)/\(finalDenominator)");
    }
    else if (wholeNumbers > 0 && remainder == 0)
    {
        // prints out whole number only
        println("Simplified fraction of \(numerator)/\(denominator) = \(wholeNumbers)");
    }
    else
    {
        // prints out fraction part only
        println("Simplified fraction of \(numerator)/\(denominator) = \(finalNumerator)/\(finalDenominator)");
    }
}

答案 2 :(得分:1)

不幸的是,没有框架可以导入以在swift或Xcode中显示分数。我建议使用您在故事板中使用的相同方法:有两个UILabelView,一个在彼此之上,在它们之间有一条线。

不是计算小数,而是使用基本数学来找到分子和分母,并将它们显示在UILabelView的顶部和底部。

此方法需要在基础级别更改您的程序,但它会起作用。