应用程序将整数转换为因子的快速代码

问题描述 投票:0回答:2

我是 swift 的新手,想要创建一个方法,该方法将以整数作为参数,并使用栅栏柱循环来打印该数字的因子。 这应该用“和”一词分隔。

例如,调用 printFactors(24) 应打印以下输出: 1、2、3、4、6、8、12、24

经过思考;我知道如何在 swift 语言之外做到这一点;但需要快速帮助。

这是我在考虑 swift 语言之前得出的结论。

public void printFactors(int n) {
   for (int i=1; i <=n; i++) {
      if (n % i == 0) {
         if (i == 1) {
            System.out.print(i);
         } 
         else {
            System.out.print(" and " + i);
         }
      } 
   }
}

非常感谢您的帮助。另外,我将如何获取“解决方案”并将其输出为标签?我会将解决方案设置为 var 吗?

swift integer factors
2个回答
1
投票

我同意@rmaddy 的观点,Stack Overflow 并不是免费的代码翻译。然而,我已经手头有类似的代码,只需要进行一些小的更改:

func factor(number: Int) -> String {
    var string = ""
    for i in 1...number {
        if number % i == 0 {
            if i == 1 {
                string += "\(i)"
            } else {
                string += "and \(i)"
            }
        }
    }
    return string
}

使用方法:

let output = factor(number: 24)
print(output) // 1 and 2 and 3 and 4 and 6 and 8 and 12 and 24

或带有标签:

let outputText = factor(number: 24)
label.text = outputText

希望这有帮助!


0
投票
func printFactors(n: Int) {
  var result: String = ""
  for i in 1...n {
    guard n % i == 0  else {continue}
    result += i == 1 ? "1" : " and \(i)"
  }
  print(result)
}

printFactors(24)
© www.soinside.com 2019 - 2024. All rights reserved.