C语言 如何在模运算前键入 uint32 数组的铸造元素



>我被迫将输出存储在unsigned int数组中。 但是,输出是数组2147483647中先前元素的线性组合的解,即 2^31-1。

下面是一个较大函数的代码片段。 很快,这个片段会产生错误的答案,因为ii会环绕xx的索引。 (请注意,xx在调用函数之前已设定种子,因此数组中的任何元素都不是空的。

#include <stdint.h>
typedef unsigned int uint32;
typedef unit_least64_t uint64;
static uint32 xx[47];
...
xx[ii] = 12345 * (uint64)(xx[i0] + xx[ii]) % 2147483647;  // i0, ii are defined elsewhere

但是,如果我们将最后一行与以下内容交换,我们将不断得到正确的解决方案。

xx[ii] = 12345 * ( (uint64)xx[i0] + (uint64)xx[ii] ) % 2147483647;

也许,这是显而易见的,但是为什么有必要对 unit64 进行两次类型转换而不是一次?

一个类型转换应该足够了,只要你把它放在正确的位置:

xx[ii] = 12345 * ( (uint64)xx[i0] + xx[ii] ) % 2147483647;

重要的是在添加之前进行强制转换以防止数字溢出,而不是在溢出已经发生时进行转换。

是的,您的初始代码可以这样编写:

uint32 t1 = xx[i0] + xx[ii]; // problem is here, result of sum is truncated as it is 32 bit
uint64 t2 = (uint64)t1;
uint64 t3 = 12345 * t2 % 2147483647;
xx[ii] = (uint32)t3;

如果您使用第二个变体,您将拥有:

uint64 t0 = (uint64)xx[i0];
uint64 t1 = (uint64)xx[ii];
uint64 t2 = t0 + t1; // no truncation, as the result is 64 bit
uint64 t3 = 12345 * t2 % 2147483647;
xx[ii] = (uint32)t3;

最新更新