gpt4 book ai didi

c++ - 长整数的意外模数行为

转载 作者:行者123 更新时间:2023-11-30 05:13:54 25 4
gpt4 key购买 nike

当操作数是(un)signedlong 时,C++ 的模% 运算符会表现得很奇怪。

为什么 mod(signed int, unsigned int)mod(signed long long int, unsigned long long int) 会产生不同的结果?如果我想要一个正确的(此处:11183),我该怎么做?

注意:如果按照我的算法,我应该调用 uint64_t mod(int64_t, uint64_t)

// Tip: 11183 is the "correct" expected result.

( int)(-3365) % ( int)(15156) = -3365
( signed int)(-3365) % ( signed int)(15156) = -3365
(unsigned int)(-3365) % (unsigned int)(15156) = 11183
( signed int)(-3365) % (unsigned int)(15156) = 11183
(unsigned int)(-3365) % ( signed int)(15156) = 11183

( long int)(-3365) % ( long int)(15156) = -3365
( signed long int)(-3365) % ( signed long int)(15156) = -3365
(unsigned long int)(-3365) % (unsigned long int)(15156) = 2555
( signed long int)(-3365) % (unsigned long int)(15156) = 2555
(unsigned long int)(-3365) % ( signed long int)(15156) = 2555

( long long int)(-3365) % ( long long int)(15156) = -3365
( signed long long int)(-3365) % ( signed long long int)(15156) = -3365
(unsigned long long int)(-3365) % (unsigned long long int)(15156) = 2555
( signed long long int)(-3365) % (unsigned long long int)(15156) = 2555
(unsigned long long int)(-3365) % ( signed long long int)(15156) = 2555

( int_fast16_t)(-3365) % ( int_fast16_t)(15156) = -3365
( uint_fast16_t)(-3365) % ( int_fast16_t)(15156) = 2555
( int_fast16_t)(-3365) % ( uint_fast16_t)(15156) = 2555
( uint_fast16_t)(-3365) % ( uint_fast16_t)(15156) = 2555

( int_fast32_t)(-3365) % ( int_fast32_t)(15156) = -3365
( uint_fast32_t)(-3365) % ( int_fast32_t)(15156) = 2555
( int_fast32_t)(-3365) % ( uint_fast32_t)(15156) = 2555
( uint_fast32_t)(-3365) % ( uint_fast32_t)(15156) = 2555

( int_fast64_t)(-3365) % ( int_fast64_t)(15156) = -3365
( uint_fast64_t)(-3365) % ( int_fast64_t)(15156) = 2555
( int_fast64_t)(-3365) % ( uint_fast64_t)(15156) = 2555
( uint_fast64_t)(-3365) % ( uint_fast64_t)(15156) = 2555

PS:关于我的系统的更多信息:

Linux pc-gi-446 4.4.0-36-generic#55-Ubuntu SMP x86_64 x86_64 x86_64 GNU/Linux
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

最佳答案

尝试

unsigned int x = -3365; printf("%u", x);

它不会打印“3365”,但会打印 unsigned int 减去 3365 + 1 的最大值,即 UINT_MAX-3365+1,即 4294963931.

因此 (unsigned int)(-3365) % (unsigned int)(15156)unsigned int z = 4294963931 % 15156 相同; printf("%u\n", z) 并给出 11183

关于c++ - 长整数的意外模数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com