使用底片时,模数返回错误结果 [英] Modulo returns wrong result when using negatives

查看:89
本文介绍了使用底片时,模数返回错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要计算: (-15%3)应该为0,但我却是1:

I want to calculate: (-15 % 3) which should be 0 but instead i'm getting 1:

当我明确地这样做时:

int IntFcn (const void *key, size_t tableSize)
{
    printf("%d\n",(*(int*)key)); // prints -15
    printf("%d\n",tableSize); // prints 3
    printf("%d\n",(-15) % 3); // prints 0
}

我得到正确的结果(0),但是当我尝试使用下面的变量时,我得到1:

I get the right result (0) but when i try to use the variables below i get 1:

int IntFcn (const void *key, size_t tableSize)
{
    printf("%d\n",(*(int*)key)); // prints -15
    printf("%d\n",tableSize); // prints 3
    printf("%d\n",((*(int*)key) % tableSize)); // prints 1
    return ((*(int*)key) % tableSize);
}

为什么会这样?

推荐答案

在第二种情况下,模的第二个操作数是无符号整数,因此在执行模之前,第一个操作数也将提升为无符号的整数.因此结果将是(unsigned)(-15) % 3,它等于(对于32位int)与4294967281 % 3 == 1.

In your second case the second operand of modulo is unsigned integer thus the first operand is promoted to unsigned as well before performing the modulo. So the result will be (unsigned)(-15) % 3 which is equal (for 32-bit int) to 4294967281 % 3 == 1.

这篇关于使用底片时,模数返回错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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