有符号整数以模无符号整数产生无意义的结果 [英] signed int modulo unsigned int produces nonsense results

查看:372
本文介绍了有符号整数以模无符号整数产生无意义的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C中执行一个真正的数学模.对我来说,允许模块化参数为负数是有意义的,因为我的模块化计算会产生负中间结果,必须将其返回到最少残差系统中.但是允许使用否定模块是没有意义的,因此我写了

I need to perform a real mathematical modulo in C. It makes sense for me to allow negative numbers for the moduled argument, since my modular calculations can produce negative intermediate results, which must be put back into the least residue system. But it makes no sense to allow negative module, therefore i wrote

unsigned int mod( int x, unsigned int m )
{
    int r = x % m;
    return r >= 0 ? r : r + m;
}

但是以负数和正数调用此类函数

However calling such function with negative number and positive module

printf("%u\n", mod(-3, 11));

产生输出

1

我不明白为什么.你能解释一下吗?

And i don't understand why. Could you please explain?

我知道运算符%与数学模不同,而且我知道它是如何为正数和负数定义的.我在问它将对不同的签名而不是不同的符号做什么.

I know operator % is different from mathematical modulo and i know how it is defined for positive and negative numbers. I was asking what it will do for different signedness, not different sign.

推荐答案

clang明确指出了您的错误:

clang with -Wconversion enabled clearly pinpoints your mistake:

prog.cc:3:15: warning: implicit conversion changes signedness: 'unsigned int' to 'int' [-Wsign-conversion]
    int r = x % m;
        ~   ~~^~~
prog.cc:3:13: warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
    int r = x % m;
            ^ ~
prog.cc:4:21: warning: operand of ? changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
    return r >= 0 ? r : r + m;
    ~~~~~~          ^
prog.cc:4:25: warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
    return r >= 0 ? r : r + m;
                        ^ ~
prog.cc:9:12: warning: implicit conversion changes signedness: 'unsigned int' to 'int' [-Wsign-conversion]
    return mod(-3, 11);
    ~~~~~~ ^~~~~~~~~~~

魔盒上的在线示例

当转换为unsigned int时,-3变为4294967293.

4294967293 % 11等于1.

这篇关于有符号整数以模无符号整数产生无意义的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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