这是应该完成任务的一种算法。与其他算法的主要区别在于,此算法始终按正确的顺序舍入数字。 最小化舍入误差。
该语言是一些伪语言,可能源自Javascript或Lua。应该说明一下。注意一个基于索引的索引(对于循环,x到y更好。
// Temp array with same length as fn.tempArr = Array(fn.length)// Calculate the expected sum.arraySum = sum(fn)lowerSum = 0-- Populate temp array.for i = 1 to fn.lengthf tempArr[i] = { result: floor(fn[i]), // Lower bound difference: fn[i] - floor(fn[i]), // Roundoff error index: i } // Original index // Calculate the lower sum lowerSum = lowerSum + tempArr[i].resultend for// Sort the temp array on the roundoff errorsort(tempArr, "difference")// Now arraySum - lowerSum gives us the difference between sums of these// arrays. tempArr is ordered in such a way that the numbers closest to the// next one are at the top.difference = arraySum - lowerSum// Add 1 to those most likely to round up to the next number so that// the difference is nullified.for i = (tempArr.length - difference + 1) to tempArr.length tempArr.result = tempArr.result + 1end for// Optionally sort the array based on the original index.array(sort, "index")


