函数参数和服用Int - Swift

时间:2014-10-16 20:00:32

标签: ios xcode swift

在我的函数中它需要两个数字是Ints我希望第一个获取变量而第二个总是设置为100这里是我的代码https://www.dropbox.com/s/h2i9up898zi4p94/Screenshot%202014-10-16%2012.52.09.png?dl=0

的屏幕截图
var firstStep2 = calculatedAnswer / 1
var secondStep2 = "\(firstStep2 * 10 * 10)"

answerLabel.text = "\(secondStep2)"
func printSimplifiedFraction(Numerator numerator: Int, Denominator denominator: Int)
  {  }

当我调用这个分数时,这就是我所说的。

printSimplifiedFraction(Numerator: 535, Denominator: 100);

当我调用此函数时,我希望分母始终为100,分子为secondStep2,如果secondStep2 = 678

printSimplifiedFraction(Numerator: secondStep2 a.k.a 678, Denominator: is always 100);

问题: 我希望我的函数取一个变量,并且分母总是设置为100

简化功能

func printSimplifiedFraction(Numerator numerator: Int, Denominator denominator = 100)
    {
        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)");
        }
    }

1 个答案:

答案 0 :(得分:1)

如果我正确捕获了它,你希望你的函数也只用第一个参数调用2个参数,给第2个参数分配一个默认值。

解决方案#1

在这种情况下,您的函数签名应如下所示:

func printSimplifiedFraction(Numerator numerator: Int, Denominator denominator: Int = 100)

解决方案#2

或者,您可以在没有第二个参数的默认值的情况下定义函数:

func printSimplifiedFraction(Numerator numerator: Int, Denominator denominator: Int)

并仅使用一个参数添加重载:

func printSimplifiedFraction(Numerator numerator: Int) {
    printSimplifiedFraction(Numerator: numerator, Denominator: 100)
}

在这两种情况下,您都可以使用一个参数调用该函数:

printSimplifiedFraction(Numerator: 10)
如果您需要不同于100的分母,

并且denominator参数将默认为100,或使其显式化:

printSimplifiedFraction(Numerator: 10, Denominator: 77)