为什么这个C程序输出负数?

发布于 2024-08-31 11:54:29 字数 395 浏览 5 评论 0原文

我已将补值分配给无符号变量。

那么为什么这个C程序会输出负数呢?

#include<stdio.h>
#include<conio.h>

int main()
{
    unsigned int Value = 4;         /*   4 = 0000 0000  0000 0100 */  
    unsigned int result = 0;

    result = ~ Value;               /* -5 = 1111 1111  1111 1011 */  

    printf("result = %d", result);  /* -5             */

    getch();

    return 0;
}

I have assigned the complement value in an unsigned variable.

Then why this C program outputs a negative number?

#include<stdio.h>
#include<conio.h>

int main()
{
    unsigned int Value = 4;         /*   4 = 0000 0000  0000 0100 */  
    unsigned int result = 0;

    result = ~ Value;               /* -5 = 1111 1111  1111 1011 */  

    printf("result = %d", result);  /* -5             */

    getch();

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苏大泽ㄣ 2024-09-07 11:54:29

%d 格式说明符指示 printf 将参数视为有符号整数。请改用 %u

The %d format specifier instructs printf to treat the argument as a signed integer. Use %u instead.

浅沫记忆 2024-09-07 11:54:29

这是因为 %d 是signed int 格式占位符,所以它被转换。使用 %u 表示无符号。

It's because %d is the signed int format placeholder, so it's getting converted. Use %u for unsigned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文