C : unsigned int 上的模运算符给出了意外的输出 [英] C : Modulus operator on unsigned int gives unexpected output

查看:93
本文介绍了C : unsigned int 上的模运算符给出了意外的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

main() {
    unsigned a = -20;
    unsigned b = 10;
    printf("%d\n", (a % b));
    printf("%d\n", (-20 % 10));
}

Output:
6
0

第二个 printf 打印预期值 0,而第一个 printf 打印 6.为什么这个带有无符号整数的意外输出?

The second printf prints the expected value of 0 while the first printf prints 6. Why this unexpected output with unsigned ints?

推荐答案

unsigned int 可以保存从 0 到 UINT_MAX 的值,没有负值.所以-20被转换为-20 + UINT_MAX + 1.

unsigned int can hold values from 0 to UINT_MAX, no negative values. So -20 is converted to -20 + UINT_MAX + 1.

在您的系统上:

(-20 + UINT_MAX + 1) % 10 != -20 % 10

这篇关于C : unsigned int 上的模运算符给出了意外的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆