C# 操作溢出尝试将有效值分配给 double

C# operation overflows trying to assign a valid value to double

我正在尝试获取 TB 中的字节数。如果我使用 Pow 函数,我没问题,但是当我明确尝试将 1024 乘以四次时,我得到一个错误。

  Console.WriteLine((double.MaxValue)); // 1.79769313486232E+308
  Console.WriteLine(Math.Pow(1024, 4)); // Clearly, 1099511627776 < MaxValue
  double d2 = 1024 * 1024 * 1024 * 1024; // error

错误CS0220:检查模式下编译时操作溢出

这是为什么?

double d2 = 1024 * 1024 * 1024 * 1024; 

The operation overflows at compile time in checked mode

因为您要创建一个整数 1024 * 1024 * 1024 * 1024,它会溢出 int.MaxValue,然后 然后 将其分配给双精度值。

double d2 = 1024.0 * 1024.0 * 1024.0 * 1024.0; 

应该可以正常工作。