c# - Int - 数字太大。如何让程序失败?

标签 c#

问题:如果一个数字超出了它的类型范围,你如何让程序失败?

下面的代码给出了小于 200 万的素数之和的错误答案,因为我使用了 int 而不是 long。

    [TestMethod]
    public void CalculateTheSumOfPrimesBelow2million()
    {
        int result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million
        Assert.AreEqual(1, result); // 1,179,908,154 .. this was what I got with an int...
                                             // correct answer was 142,913,828,922 with a long
    }



public static class PrimeTester
{
    public static int calculateTheSumOfPrimesBelow(int maxPrimeBelow)
    {
        // we know 2 is a prime number
        int sumOfPrimes = 2;
        int currentNumberBeingTested = 3;
        while (currentNumberBeingTested < maxPrimeBelow)
        {
            double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested);

            bool isPrime = true;
            for (int i = 2; i <= squareRootOfNumberBeingTested; i++)
            {
                if (currentNumberBeingTested % i == 0)
                {
                    isPrime = false;
                    break;
                }
            }

            if (isPrime)
                sumOfPrimes += currentNumberBeingTested;

            currentNumberBeingTested += 2; // as we don't want to test even numbers
        }
        return sumOfPrimes;
    }
}

最佳答案

或者添加checked()围绕可能溢出/下溢或添加 /checked+ 的语句到你的编译选项

关于c# - Int - 数字太大。如何让程序失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4536523/

相关文章:

c# - 在 web.config 中配置的 UnityContainer

c# - 关于将 List<T> 打印到屏幕的问题

c# - 如何使用 native 应用程序 C# XAML 在 Azure AD 上创建新用户?

C#新建进程窗口不隐藏

c# - 如何通过引用传递 System.Action?

c# - Gridview刷新问题

c# - 如何使用 Microsoft Graph 客户端添加扩展?

c# - 错误 CS1014 : A get or set accessor expected

c# - 减小位图图像的物理尺寸?

c# - 对于 R# 对精度损失的提示,这是一个很好的解决方案吗?