函数将浮点值四舍五入到具有特定允许小数的最近浮点值
Function to round a float to nearest float with specific allowed decimals
我正在尝试编写一个函数,它的行为类似于以下(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
相关文章:
- C++将浮点指针值舍入为小数位数
- 从给定的 I 和 D 序列中形成最小数
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- 计算 PI 最多 42 位小数
- 为什么我必须添加一个小数才能在C++中正确计算此数学
- 返回浮点数的小数位数
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 在数学上将浮点数四舍五入到 N 位小数
- 打印双精度的整个非小数部分
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- 如何在C++中对OpenCV垫的小数进行四舍五入?
- 将 int 数组转换为带有小数C++的双精度数组
- Arduino如何制作返回固定大小数组的函数
- 从浮点数中删除小数部分但保留类型的有效方法
- 分配新的零大小数组可以具有有效价值吗?
- c++只关心2位小数,没有设置精度
- 有没有一种方法可以在不设置精度的情况下设置小数位数
- gcc c++编译器中的零大小数组
- 给出了一个数的确切除数(n),如何确定具有n个除数的最小数?