假设我想计算数据集的平均值,例如
class Averager {
float total;
size_t count;
float addData (float value) {
this->total += value;
return this->total / ++this->count;
}
}
total
or值迟早count
会溢出,所以我让它不记得总值:
class Averager {
float currentAverage;
size_t count;
float addData (float value) {
this->currentAverage = (this->currentAverage*count + value) / ++count;
return this->currentAverage;
}
}
看起来它们会溢出更长的时间,但是和之间的乘法average
会count
导致溢出问题,所以下一个解决方案是:
class Averager {
float currentAverage;
size_t count;
float addData (float value) {
this->currentAverage += (value - this->currentAverage) / ++count;
return this->currentAverage;
}
}
似乎更好,下一个问题是如何防止count
溢出?