我需要将23名学生分成5组,所以
Dim i as Integer = 23 Mod 5
给出余数= 3。
如何分配剩余部分,使第一,第二和第三组的成员比其他成员多一个?
或者如何反向开始分发,第五,第四和第三将有1个额外成员?
我想得到这个值:
Dim groups(4) As Integer
groups(0) = 5
groups(1) = 5
groups(2) = 5
groups(3) = 4
groups(4) = 4
答案 0 :(得分:0)
所以,这是你的设置:
Dim groups As Integer() = New Integer(4) {}
Dim students As Integer = 23
您知道如何计算组大小和余数:
Dim groupSize As Integer = students \ groups.Length ' \ is integer division
Dim remainder As Integer = students Mod groups.Length
然后浏览每个组并为其指定大小:
For i As Integer = 0 To groups.Length-1
groups(i) = groupSize
Next
最后,您需要分配剩余部分。根据您的问题,您希望在第一个余数组中添加1。
转换为:
For i As Integer = 0 To remainder-1
groups(i) = groups(i) + 1
Next
答案 1 :(得分:0)
这对我有用:
Dim value = 23
Dim divisor = 5
Dim remainder = value Mod divisor
Dim groups(divisor - 1) As Integer
For i = 0 To divisor - 1
groups(i) = value \ divisor + If(i < remainder, 1, 0)
Next
答案 2 :(得分:0)
您可以尝试以下代码
Dim r As Integer = 23 Mod 5
Dim d As Integer = 23 \ 5
Dim group(4) As Integer
For i = 0 To group.Length - 1
group(i) = d
If r > 0 Then
group(i) += 1
r -= 1
End If
Next