我正在嘗試撰寫一個行為如下的函式(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() 方法,但只允許使用特定的小數值
我已經考慮了一段時間,但我一直在努力想出一個好的解決方案,任何想法都將不勝感激!
uj5u.com熱心網友回復:
@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;
}
uj5u.com熱心網友回復:
遵循@High Performance Marks 的建議,我創建了以下內容:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421397.html
標籤:
