如何检查unsigned int变量是否包含负数?

时间:2016-02-16 05:40:20

标签: c unsigned-integer

我有以下代码:

int main()
{ 
    int i;
    unsigned int j;

    printf("Type a number:  ");
    scanf("%d", &i);

    j = i;

    if (________)
    {
        printf("Negative!\n");
    }

    return 0;
}

我会在if语句中添加什么来检查无符号变量" j"包含负数?

4 个答案:

答案 0 :(得分:2)

你可以这样做:

  if((int)j < 0) 
  {
   printf("Negative!\n");
  }

答案 1 :(得分:1)

您可以检查变量i,例如

if ( i < 0 )
{
    //...
}

或者你可以写例如

if ( j > INT_MAX )
{
    //...
}

因为类型int的非负值的内部表示与类型unsigned int的相同值的内部表示一致。至少它适用于整数的2补码表示。

最后你可以查看符号位。

答案 2 :(得分:0)

这是一种方法:

#include<stdio.h>
/* This is in easier to verify example.
 * I have used char to represent integers that fits in one byte.
 * char is one byte in my system
 * In case of an overflow, the numbers are wrapped around.
 * You could check with bigger types as you please.
 */

int main(void)
{
unsigned char x;
char y;
        printf("Size of char is %zd\n",sizeof(char));
        printf("Enter an integer : ");
        scanf("%d",&x);
        y=x;
        printf("Number is %s when converted to signed\n",\
                             (y>=0?"positive":"negative"));
return 0;
}

使用INT_MININT_MAX检查相同内容需要包含limits.h头文件。指点位操作 大卫出来是另一种选择。

答案 3 :(得分:0)

int i;
unsigned int j;

// store a value in i

j = i;

测试j是否包含负数:

if (0)
{
    printf("Negative!\n");
}

无符号整数永远不会保持负值。

如果i的值为负数,则在将其分配给j时,它将转换为某个正值。如果您想知道i的值是否为负值,则应测试i,而不是j

if (i < 0) {
    puts("i is negative");
}
else {
    puts("i is not negative");
}
puts("j is not negative");

请注意,将j的值转换回int并不可靠。将值超过INT_MAX的值转换为类型int会产生实现定义的结果(或引发实现定义的信号)。您很可能会恢复i的原始值,但为什么要这么做呢?如果您想测试i的值,请测试i的值。

相关问题