dotnet core 中数值溢出

.net core中使用C#的int类型,存在数值上下限范围,如下:

int max = int.MaxValue;
int min = int.MinValue;
Console.WriteLine($"The range of integers is {min} to {max}");

运行得到结果

The range of integers is -2147483648 to 2147483647


此时如果执行以下代码

int what = max + 3;
Console.WriteLine($"An example of overflow: {what}");

得到范围结果是

An example of overflow: -2147483646

很奇怪,执行max+3得到结果成了min+2

查询官方教程

If a calculation produces a value that exceeds those limits, you have an underflow or overflow condition.

如果计算产生的值超过这些限制,则会出现下溢溢出情况。

max+3发生了下溢,则变为min+2了。

这在Python中却是另外一种光景

import sys

print sys.maxint

得到最大值2147483647

然执行以下

print sys.maxint+3

得到2147483650

看到没,没有溢出,原来Python在int超出最大值后,自动将之转为long类型,所以就不存在溢出了,只要内存足够大。

猜你喜欢

转载自www.cnblogs.com/lnkDel/p/9395026.html