奇数整数除法

时间:2017-12-15 12:10:07

标签: swift

var number = numberCars/ (categories?.count)! 

numberCars是汽车数量,categories?.count汽车类别数量,number是分配给每个类别的汽车数量,例如numberCars = 4和{{} {1}} 4/2 = 2我们已经为类别分配了2辆汽车。不幸的是,这项工作只有在我有偶数的情况下,我如何处理categories?.count = 2numberCars = 7这样的情况?在这种情况下,我想将3辆汽车分配给一个类别,将2辆汽车分配给其余类别。

2 个答案:

答案 0 :(得分:1)

假设您在numberOfCars对象中有Category变量,那么您可以使用简单算术来计算您的需求。此代码未经过优化,您可以优化此代码。这只是让你了解如何做到这一点

let number = numberCars/categories.count
let remainder = numberCars % categories.count


print("avg cars:\(number) remainder:\(remainder)")

// Assign the avg cars to all category
for category in categories {
  category.numberOfCars = number
}

// Increment the categories to fit the remaining cars
for i in 0..<remainder {
  categories[i].numberOfCars += 1
}


for category in categories {
  print("# cars \(category.numberOfCars)")
}

答案 1 :(得分:0)

优化代码。

let remainder = numberCars % categories.count

if numberCars > categories.count {
  // Assign the avg cars to all category
  for category in categories {
    category.numberOfCars = categories.count
  }
}

// Increment the categories to fit the remaining cars
for i in 0..<remainder {
  categories[i].numberOfCars += 1
}


for category in categories {
  print("# cars \(category.numberOfCars)")
}