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

标签 c# double overflow

我正在尝试获取 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 值。

double d2 = 1024.0 * 1024.0 * 1024.0 * 1024.0; 

应该可以正常工作。

关于C# 操作溢出尝试将有效值分配给 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33508630/

相关文章:

c# - 使用 EF 的 DbContext.ExecuteSqlCommand() 进行交易时出现异常

c# - ServiceStack - 处理 'Parameter is never used' 警告

c++ - 左移一个 'double' 操作数

swift - iOS - 将字符串转换为 double

Java 小数点之间的 double 计算

python - 为什么 Python 不抛出溢出错误?

c# - 需要有关在 C# 中使用 XMLText 的建议

c# - 将控制台应用程序移植到 winforms C#,静态类型错误

css - 元素可能到 'escape' 具有固定尺寸和溢出 :hidden? 的 div 的约束边界

jquery - 使用面板动画禁用滚动