我尝试编写一个在不受约束的输入下表现良好的累加器。这似乎不是微不足道的,需要一些非常严格的计划。这真的很难吗?
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;
}
编辑:我已删除了样式偏见
答案 0 :(得分:5)
您是否考虑过:
if ( max - *accumulator < amount )
return 1;
*accumulator += amount;
return 0;
在&#34; naive&#34;中改变你的第一次比较的方向您避免溢出的版本,即查看剩余多少空间(安全)并将其与要添加的数量(也是安全的)进行比较。
此版本假定在调用函数时*accumulator
从未超过max
;如果您想支持这种情况,那么您必须添加额外的测试。