我有以下函数,它应该可以与 for 循环一起正常工作,以分析一系列 double 结果是否已“稳定”。我写的内容总共分析了 3 个点,我想知道如何接受一个名为“minNumberOfSamples”的变量并让它比较这么多结果?
bool MeasurementStabilized(double newResult, double percentageThreshold, double limitRange)
{
static double meas1 = 1E100;
static double meas2 = 1E100;
if ((abs(newResult - meas2) / limitRange >= percentageThreshold) ||
(abs(meas2 - meas1) / limitRange >= percentageThreshold))
return TRUE;
meas1 = meas2;
meas2 = newResult;
return FALSE;
}
最佳答案
我想在@John Coleman 的帮助下我现在已经很接近了。这似乎可以完成这项工作,但如果有人能想到的话,我们正在寻求一些改进:
static double* gArr;
void MeasurementStabilizedCleanup(void)
{
free(gArr);
}
static bool MeasurementStabilized(double newResult, double percentageThreshold, double limitRange, int minNumberOfSamples)
{
static bool firstRun = TRUE;
bool retVal = TRUE;
int x;
//init variables
if (firstRun)
{
gArr = malloc((minNumberOfSamples + 1) * sizeof(double));
for(x = 0; x <= minNumberOfSamples; x++)
{
gArr[x] = 1E100;
}
firstRun = FALSE;
}
//loop through each value comparing it to the latest result
for(x = minNumberOfSamples - 1; x >= 0; x--)
{
gArr[x + 1] = gArr[x]; //4 -> 5 , 3 -> 4, ...
if (fabs(newResult - gArr[x]) / limitRange >= percentageThreshold)
retVal = FALSE;
}
gArr[0] = newResult; //dont forget to update the latest sample
return retVal;
}
void main(void)
{
double doubles[] = {1, 2, 4, 4, 4, 4, 4};
int x;
for (x = 0; x <= 6; x++)
{
if(MeasurementStabilized(doubles[x], 0.01, 4, 4))
{
;
}
}
MeasurementStabilizedCleanup();
}
关于c - 如何用C编写函数 'extensible'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545769/