【问题标题】:An issue with 32 bit * 32 bit data in C#C# 中 32 位 * 32 位数据的问题
【发布时间】:2012-03-13 05:08:16
【问题描述】:

我有这个代码乘以 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);
    }

但是,结果并不完全符合我的预期。

这是怎么回事?

【问题讨论】:

    标签: c# .net math int


    【解决方案1】:

    溢出。结果计算为 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);
    }
    

    【讨论】:

      【解决方案2】:

      Int32 * Int32 == Int32

      您需要在乘法之前将 x 和 y 转换为 Int64

      (Int64)Int32 * (Int64)Int32 == Int64

      【讨论】:

        【解决方案3】:

        在乘法中将 x 或 y 转换为 Int64。乘法的输出基于源类型,而不是目标类型。

        【讨论】:

          【解决方案4】:

          Int32 * Int32 产生另一个 Int32。结果溢出了。

          试试:

          System.Int64 x, y;
          

          【讨论】:

            猜你喜欢
            • 2011-07-31
            • 2013-03-19
            • 2013-09-18
            • 2017-02-03
            • 1970-01-01
            • 2011-12-12
            • 1970-01-01
            • 1970-01-01
            • 2022-06-17
            相关资源
            最近更新 更多