【问题标题】:How to calculate height based on item count in swift如何在swift中根据项目数计算高度
【发布时间】:2021-09-22 08:42:49
【问题描述】:

如何使用简单的数学公式存档此结果。

我有一个初始offset = 100 和初始count = 0,我想根据count 值增加偏移量。我尝试使用下面的代码,但它不能正常工作。

例子

  1. 当计数为03 时,偏移量应为100
  2. 当计数为 46,那么偏移量应该是 200
  3. 当计数为79 时, 那么偏移量应该是300
  4. 当计数为1012 时,则偏移 应该是400

尝试

func getHeight(count: Int) ->CGFloat {
     var index = 0
     for i in 0..<count{
         if(i % 2  != 0){
             index += 1
         }
     }
    return CGFloat(100 * index)
    //return CGFloat(count + 3 / 9 * 100)
}

测试

print("0 to 3 = \(self.getHeight(count: 0)), expected = 100")
print("0 to 3 = \(self.getHeight(count: 2)), expected = 100")
print("4 to 6 = \(self.getHeight(count: 4)), expected = 200")
print("7 to 9 = \(self.getHeight(count: 7)), expected = 300")
print("10 to 12 = \(self.getHeight(count: 12)), expected = 400")

结果

0 to 3 = 0.0, expected = 100
0 to 3 = 100.0, expected = 100
4 to 6 = 200.0, expected = 200
7 to 9 = 300.0, expected = 300
10 to 12 = 600.0, expected = 400

【问题讨论】:

标签: swift math


【解决方案1】:

整数除法公式:

let cnt = count != 0 ? count : 1
result = 100 * ((cnt + 2) / 3)

【讨论】:

  • 这对count = 0 不起作用
  • @Alladinian 是的,我没有注意到 0 的范围更广
  • 三元运算符的替代方法是使用guard 语句guard count &gt; 0 else { return 100 }
  • 或没有警卫:max(1, (count + 2) / 3) * 100.0
猜你喜欢
  • 1970-01-01
  • 2022-10-18
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多