没有溢出异常在C#中诠释? [英] No overflow exception for int in C#?

查看:102
本文介绍了没有溢出异常在C#中诠释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题的10号在项目欧拉(伟大的网站的方式)这个奇怪的经历。该任务是计算低于200万的所有质数的总和。

I had this weird experience with problem number 10 on Project Euler (great site by the way). The assignment was to calculate the sum of all the prime numbers below two million.

我用的总和一个int,我的algorith产生一个答案,但是当我粘贴它来验证答案,这是不对的。

I used an int for the sum, and my algorith produced an answer, but when i pasted it to verify the answer, it was wrong.

原来结果是太大,以适应一个int,但不会导致这种溢出错误的东西?相反,它距离真正的答案返回的值不远了。

It turned out that the result was too big to fit in an int, but wouldn't this cause an overflow error or something? Instead, it just returned a value far off from the real answer.

当我改变的类型长,一切都虎背熊腰,脚蹬dory没问题。

When I changed the type to long, everything was hunky dory.

推荐答案

C#整数运算默认不扔在溢出异常。你可以做到这一点通过项目设置,或者通过检查计算

C# integer operations don’t throw exceptions upon overflow by default. You can achieve that via the project settings, or by making the calculation checked:

int result = checked(largeInt + otherLargeInt);

现在的操作将抛出。

相反的是选中,这使得任何操作明确选中。显然,这只能是有道理的,当你有在项目设置中启用检查操作。

The opposite is unchecked, which makes any operation explicitly unchecked. Obviously, this only makes sense when you’ve got checked operations enabled in the project settings.

这篇关于没有溢出异常在C#中诠释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆