コードでこの問題を解決するための最良の方法は何ですか?
問題は、私が2ドルの金額(ポットと呼ばれる)を持っていることです。これは3人に割り当てる必要があります。各人は両方のポットから得られる特定の金額を受け取り、レートはほぼ同じでなければなりません。割り当ての合計が多すぎたり少なすぎたりする丸めの問題に遭遇し続けます。
具体的な例を次に示します。
ポット#1 987,654.32
ポット#2 123,456.78
人#1は割り当て量を取得します:345,678.89
人#2は割り当て量を取得します:460,599.73
人#3は割り当て量を取得します:304,832.48
私のロジックは次のとおりです(コードはc#にあります):
foreach (Person person in People)
{
decimal percentage = person.AllocationAmount / totalOfAllPots;
decimal personAmountRunningTotal = person.AllocationAmount;
foreach (Pot pot in pots)
{
decimal potAllocationAmount = Math.Round(percentage * pot.Amount, 2);
personAmountRunningTotal -= potAllocationAmount;
PersonPotAssignment ppa = new PersonPotAssignment();
ppa.Amount = potAllocationAmount;
person.PendingPotAssignments.Add(ppa);
}
foreach (PersonPotAssignment ppa in person.PendingPotAssignments)
{
if (personAmountRunningTotal > 0) //Under Allocated
{
ppa.Amount += .01M;
personAmountRunningTotal += .01M;
}
else if (personAmountRunningTotal < 0) //Over Allocated
{
ppa.Amount -= .01M;
personAmountRunningTotal -= .01M;
}
}
}
私が得た結果は次のとおりです。
ポット#1、人#1 = 307,270.13
ポット#1、人#2 = 409,421.99
ポット#1、人#3 = 270,962.21
ポット#1合計= 987,654.33(1ペニーオフ)
ポット#2、人#1 = 38,408.76
ポット#2、人#2 = 51,177.74
ポット#2、人#3 = 33,870.27
ポット#2合計= 123,456.77(1ペニーオフ)
ポットの合計は、元の合計と一致する必要があります。
私は何かが足りないか、私が取らなければならない余分なステップがあるかもしれないと思います。私は正しい方向に進んでいると思います。
どんな助けでも大歓迎です。