递增整数值超出其整数限制 - C#

发布于 2024-09-06 12:39:31 字数 281 浏览 3 评论 0原文

我有一个 for 循环,它不断增加整数值直到循环完成。因此,如果限制 n 是双精度变量,并且增量变量“i”是整数,则 i 的增量会超出其限制。

 double total = 0;
 double number = hugetValue;
 for (int i = 1; i <= number; i++)
 {
    total = total + i;
 }
 return total;

如果“i”超出其容量,会发生什么情况? i 的值如何变化?我会收到运行时错误吗?

I've a for loop which keeps incrementing an integer value till the loop completes. So if the limit n is a double variable and the incremented variable 'i' is an integer, i gets incremented beyond its limits.

 double total = 0;
 double number = hugetValue;
 for (int i = 1; i <= number; i++)
 {
    total = total + i;
 }
 return total;

What happens to 'i' if it exceeds its capacity? How the value of i changes? Will i get a runtime error?

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

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

发布评论

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

评论(3

坦然微笑 2024-09-13 12:39:31

与 C 的某些实现中的行为类似,其中 int 只是从 INT_MAX 回绕到 INT_MIN(尽管根据 ISO 标准,这实际上是未定义的行为),C# 也会回绕。在 VS2008 中使用以下命令进行测试:

int x = 2147483647;
if (x+1 < x) {
    MessageBox.Show("It wrapped...");
}

将导致出现消息框。

如果您的 HugetValue 大于最大 int 值,那么您的循环将因此永远运行。

例如,如果它是 2147483648,当您认为自己已经接近它时,int 会从 2147483647 回绕到 -2147483648 并且循环继续进行。

Similar to the behaviour in some implentations of C where an int just wraps around from INT_MAX to INT_MIN ( though it's actually undefined behaviour according to the ISO standard), C# also wraps. Testing it in VS2008 with:

int x = 2147483647;
if (x+1 < x) {
    MessageBox.Show("It wrapped...");
}

will result in the message box appering.

If your hugetValue is greater than the maximum int value, then your loop will run forever because of this.

For example, if it's 2147483648, just as you think you're getting close to it, the int wraps around from 2147483647 back to -2147483648 and the loop just keeps on going.

2024-09-13 12:39:31

如果您想要异常,请提供 checked 编译器选项,或使用 C# 中提供的 checked 构造。

If you want an exception, either supply the checked compiler option, or use the checked construct provided in C#.

萌︼了一个春 2024-09-13 12:39:31

如果这看起来很粗鲁,我深表歉意,但通过亲自尝试,您会学到更多东西。

编辑:啊哈,所以你确实尝试过,并得到了意想不到的结果。正如其他地方所解释的,类 C 语言倾向于悄悄地包装整数算术。如果检查溢出的成本很高,那么这实际上是一种相当合理的行为。一旦您知道这种情况可能会发生,请仔细编码,特别是注意示例中的构造类型。

Apologies if this seems rude, but you will learn far more by trying this yourself.

Edited: aha, so you did try it, and got unexpected results. As has been explained elsewhere C-like languages tend to quietly wrap integer arithmetic. That's actually quite a reasonable behaviour in general if the cost of checking for overflow is high. Once you know that this can happen one codes carefully, especially watching for the kind of construct in your example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文