C# 中常量值计算错误溢出

发布于 2025-01-06 21:29:07 字数 238 浏览 5 评论 0原文

我需要分配整数(或其他数据类型)的常量值。

我在作业中遇到“无法转换...”错误。

在此处输入图像描述

投射似乎无法处理“溢出...”错误。

在此处输入图像描述

这有什么问题吗?

I need to assign constant value in integer (or other data type).

I got "Cannot convert ..." error with the assignment.

enter image description here

Casting doesn't seem to work with "Overflow ..." error.

enter image description here

What's wrong with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

缺⑴份安定 2025-01-13 21:29:07

您在常量中定义了太多F。使用0xFFFFFFFF,编译器必须选择一个支持0xFFFFFFFF值的存储位置。 Int32 的最大正值是 0x7FFFFFFF,因此编译器会正确地出错。唯一可以保存 0xFFFFFFFF 的类型是 uint 或 64 位存储之一。

要解决此问题,只需使用 Int32.MaxValue

int i32 = Int32.MaxValue;

You've defined too many Fs in the constant. Using 0xFFFFFFFF the compiler must choose a a storage location that supports a positive value of 0xFFFFFFFF. The max positive value of an Int32 is instead 0x7FFFFFFF and hence the compiler correctly errors. The only types which can hold 0xFFFFFFFF are uint or one of the 64 bit storages.

To fix this just use Int32.MaxValue

int i32 = Int32.MaxValue;
瞄了个咪的 2025-01-13 21:29:07

32 位 int 可以表示的最大(最大正数)数字是 0x7fffffff。前面出现 7 而不是另一个 f 是因为 int 有符号,所以最高位代表数字的符号(正或负)。

在第一个示例中,编译器看到一个只能由 unsigned int 表示的数字,因此它假设它是 UInt32。这无法转换为 int,因此会出现错误。

在第二个示例中,您使用强制转换来强制转换,但数字不适合 int,因此会发生溢出(数字太大)。

为了避免溢出,选项包括:

  • 分配 -1
  • 未检查的 {} 块中分配 0xffffffff,以便写入原始二进制值而不检查溢出。这将读回 -1。
  • 使用可以表示较大正数的更宽类型(例如 uint 或 long)。不过,这不会被视为 -1,它将是一个很大的正值。

The maximum (largest positive) number a 32 bit int can represent is 0x7fffffff. The 7 at the front occurs rather than another f is because int is signed, so the top bit represents the sign (positive or negative) of the number.

In your first example the compiler sees a number that can only be represented by an unsigned int, so it assumes it is a UInt32. This cannot be converted to an int, hence the error.

In your second example you are forcing the conversion with a cast, but the number won't fit into an int, so an overflow (number too big) occurs.

To avoid an overflow, options include:

  • Assign a -1
  • Assign 0xffffffff in an unchecked {} block so the raw binary value is written without checking for an overflow. This will read back as -1.
  • Use a wider type that can represent the larger positive number (uint or long, for example). This won't be considered a -1 though, it'll be a large positive value.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文