无符号数与有符号数交叉运算
在一般的混合运算中,如果存在有符号数与无符号数交织运算,这个时候必须主要计算结果的符号位转换,下面举例说明一下:
#include <stdio.h>
int main(void)
{
unsigned int a = 2;
int b = -20;
if(a + b > 6)
{
printf("%s\n", "a+b > 6");
}
else
{
printf("%s\n", "a+b < 6");
}
return 0;
}
上面的输出结果为:
a+b > 6
因为上面有符号的a与无符号的b之间做混合运算,系统默认转换为了无符号数,导致上面的运算错误,所以当你存在混合算数运算时一定要非常小心,这些错误不易发现,且非常消耗时间。
下面再举例说明一下:
#include <iostream>
int main(void)
{
uint32_t num1 = 2;
uint32_t num2 = 3;
int32_t num3 = (num1-num2)/num1;