递增整数值超出其整数限制 - C#
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与 C 的某些实现中的行为类似,其中
int
只是从 INT_MAX 回绕到 INT_MIN(尽管根据 ISO 标准,这实际上是未定义的行为),C# 也会回绕。在 VS2008 中使用以下命令进行测试:将导致出现消息框。
如果您的 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:will result in the message box appering.
If your
hugetValue
is greater than the maximumint
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, theint
wraps around from2147483647
back to-2147483648
and the loop just keeps on going.如果您想要异常,请提供
checked
编译器选项,或使用 C# 中提供的checked
构造。If you want an exception, either supply the
checked
compiler option, or use thechecked
construct provided in C#.如果这看起来很粗鲁,我深表歉意,但通过亲自尝试,您会学到更多东西。
编辑:啊哈,所以你确实尝试过,并得到了意想不到的结果。正如其他地方所解释的,类 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.