函数将浮点值四舍五入到具有特定允许小数的最近浮点值

Function to round a float to nearest float with specific allowed decimals

本文关键字:许小数 小数 最近 四舍五入 函数      更新时间:2024-09-27

我正在尝试编写一个函数,它的行为类似于以下(c++,但用任何可接受的语言回答(

float roundToGivenDecimals(float input, float allowedDecimals[])

用法:

float roundToGivenDecimals(10.4, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 10.45
float roundToGivenDecimals(3.15, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 3.15
float roundToGivenDecimals(3.01, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 2.99

类似于标准的round((方法,但只允许使用特定的分数值

我已经考虑了一段时间,但我正在努力想出一个好的解决方案,任何想法都将不胜感激!

@Daniel Davies,我稍微改变了你的答案,现在它正常工作:

double roundToGivenDecimals(double input, double allowedDecimals[], int numAllowedDecimals) {
double inputFractional = input - floor(input);
double result = input;
double minDiff = 1;
for (int i = 0; i < numAllowedDecimals; ++i) {
if (fabs(inputFractional - allowedDecimals[i]) < minDiff) {
result = floor(input) + allowedDecimals[i];
} else if (fabs(inputFractional + 1 - allowedDecimals[i]) < minDiff) {
result = floor(input) - 1 + allowedDecimals[i];
}
minDiff = fabs(input - result);
}
return result;
}

根据@高性能标记的建议,我创建了以下内容:

float roundToGivenDecimals(float input, float allowedDecimals[], int numAllowedDecimals) {
double inputIntegral;
double inputFractional; 
inputFractional = modf(input, &inputIntegral);
float minAbsValue;
int minAbsValueIndex;
for(int i = 0; i < numAllowedDecimals; i++) {
float allowedDecimalMinusFractional = allowedDecimals[i] - inputFractional;
float absVal = abs(allowedDecimalMinusFractional);
if (absVal < minAbsValue || i == 0) {
minAbsValue = absVal;
minAbsValueIndex = i;
}
}
return inputIntegral + allowedDecimals[minAbsValueIndex];
}

这基本上是正确的,并且适用于我的目的,但在某些情况下,该功能可能无法按预期运行:

float roundToGivenDecimals(10.4, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 10.45 correct
float roundToGivenDecimals(3.15, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 3.15 correct
float roundToGivenDecimals(3.01, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 3.1 <-- this is incorrect, the expected output should be 2.99