我正在尝试编写一个累加器,它在无约束输入的情况下表现良好。这似乎并不琐碎,需要一些相当严格的计划。真的这么难吗?
int naive_accumulator(unsigned int max,
unsigned int *accumulator,
unsigned int amount) {
if(*accumulator + amount >= max) {
return 1; // could overflow
}
*accumulator += max; // could overflow
return 0;
}
int safe_accumulator(unsigned int max,
unsigned int *accumulator,
unsigned int amount) {
// if amount >= max, then certainly *accumulator + amount >= max
if(amount >= max) {
return 1;
}
// based on the comparison above, max - amount is defined
// but *accumulator + amount might not be
if(*accumulator >= max - amount) {
return 1;
}
// based on the comparison above, *accumulator + amount is defined
// and *accumulator + amount < max
*accumulator += amount;
return 0;
}编辑:我已经删除了风格偏见。
发布于 2014-08-19 22:24:12
你有否考虑过:
if ( max - *accumulator < amount )
return 1;
*accumulator += amount;
return 0;通过在“朴素”版本中更改第一个比较的方向,可以避免溢出,即查看还剩多少空间(安全),并将其与要添加的金额进行比较(也是安全的)。
此版本假设在调用函数时*accumulator从未超过max;如果要支持这种情况,则必须添加额外的测试。
https://stackoverflow.com/questions/25393881
复制相似问题