c# - C# 中 32 位 * 32 位数据的问题

标签 c# .net math int

我有这段代码可以乘以 32 位 * 32 位。

public static void RunSnippet()
{
    System.Int32 x, y;
    System.Int64 z;

    System.Random rand = new System.Random(DateTime.Now.Millisecond);
    for (int i = 0; i < 6; i++)
    {
        x = rand.Next(int.MinValue, int.MaxValue);
        y = rand.Next(int.MinValue, int.MaxValue);
        z = (x * y);
        Console.WriteLine("{0} * {1} = {2}", x, y, z);
    }

然而,结果并不是我所期望的。

enter image description here

这是怎么回事?

最佳答案

溢出。结果计算为 32 位整数,然后提升为 64 位。为避免这种情况,请在乘法之前将因子转换为 64 位。

System.Int32 x, y;
System.Int64 z;

System.Random rand = new System.Random(DateTime.Now.Millisecond);
for (int i = 0; i < 6; i++)
{
    x = rand.Next(int.MinValue, int.MaxValue);
    y = rand.Next(int.MinValue, int.MaxValue);
    z = ((Int64)x * y); //by casting x, we "promote" the entire expression to 64-bit.
    Console.WriteLine("{0} * {1} = {2}", x, y, z);
}

关于c# - C# 中 32 位 * 32 位数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9402135/

相关文章:

c# - 获取文化特定日期的日和月部分

math - 在graphviz中使用符号字体/数学符号

c# - ListView 上下文菜单上的命令绑定(bind)未触发(未找到)?

c# - 从 C# 窗体启动 VB 窗体

c# - StackPanel.Children.Clear() 无法正常工作

c# - 如何实现单机单实例应用?

c# - 如何在 C# 中刷新列表框?

.net - 商业软件的视频编码器许可

javascript - math - 在 Javascript 中获取旋转后的图像尺寸

arrays - 找到两个集合之间所有可能的双射