计算两个unsigned int c++的绝对差

问题描述 投票:0回答:1

计算两个无符号整数之差的绝对值时如何防止溢出? 结果也必须是无符号整数(实际上独立于处理器,因为它在数学上只是 0 到 MAXINT 之间的数字)。

unsigned int a;
unsigned int b;

abs(a-b);

但这仅在以下情况下才有效<=a, otherwise a-b<0 and will then overflow, taking abs later will not help.

进行该计算的最简单的溢出安全方法是什么?其实我想测试是否 |a-b|

感谢评论中的答案,人们看到可以像使用案例区分一样完成一个简单的解决方案。

bool uint_diff(unsigned int a, unsigned int b){
  if (a > b){
    return (a - b);
  }
  else {
    return (b - a);
  }
}
c++ overflow unsigned unsigned-integer absolute-value
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.