gpt4 book ai didi

C# ulong 溢出/下溢以某种方式允许

转载 作者:行者123 更新时间:2023-11-30 23:10:36 30 4
gpt4 key购买 nike

我对 ulong 类型的行为有点困惑。我理解它是 64-bit integer used for positive numbers (最大值 18,446,744,073,709,551,615)。我刚开始使用它是因为我需要非常大的正数,但有一些我不理解潜在负数的奇怪行为。

ulong big = 1000000;    //Perfectly legal

ulong negative = -1; //"Constant value "-1" cannot be converted to a ulong" Makes sense


//Attempt to sneak around the -1 as a constant compile-time error
int negativeInt = -1;
ulong negativeUlongFail = negativeInt; //"Cannot implicitly convert 'int' to 'ulong'.
//An explicit conversion exists (are you missing a cast?)"
//So I add casting
ulong negativeUlong = (ulong)negativeInt; //But this yields 18446744073709551615

//Try and get a negative number indirectly
ulong number = 0;
number = number - 10; //now number is 18446744073709551615 but no underflow error

这是怎么回事?为什么有些下溢错误会被捕获,而另一些则不会甚至不抛出异常?我可以检测到这些吗?

我专注于通过下溢获得负数,但在获得大于最大值和溢出的数字时我也看到过类似的情况。

我不确定它们在技术上是错误还是异常,所以如果我使用了不正确的术语,请原谅我

最佳答案

如果你想抛出下溢(或溢出)异常,试试这个:-

checked
{
ulong number = 0;
number = number - 10;
}

默认情况下,异常会被吞噬(它以未经检查的方式运行)。

查看官方文档

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/checked

关于C# ulong 溢出/下溢以某种方式允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270715/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com