#、Java、JavaScript 和 Python 中的数字溢出管理

2022/11/5 1:23:55

本文主要是介绍#、Java、JavaScript 和 Python 中的数字溢出管理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

C#

在 C# 中,递增最大值时,不会收到数字溢出异常(这是默认行为)。请看下面的代码片段,其中最大整数值 (2147483647) 递增 1。

int count=int.MaxValue;
Console.WriteLine($"count is {++count}");

在这种情况下,输出将2147483648这显然是溢出,因为我们在正数增量后得到一个负数。发生这种情况是因为增量上升了数字中最高有效位,即符号位(+/-)。

要触发溢出/下溢异常,我们需要将操作放在选中的块中,如下所示:

int count = int.MaxValue;
checked
{
    Console.WriteLine($"count is {++count}");
}

我们开始了,例外已经送达!
'System.OverflowException' in overflow-dotnet.dll: 'Arithmetic operation resulted in an overflow.'

C# 编译器中,您可以启用选项检查溢出下溢,其中默认上下文是已检查上下文并启用溢出检查(以及补充,您可以使用关键字uncheck来取消选中上下文)。

爪哇岛

在 Java 中,行为与 C# 中发生的行为非常相似,请查看以下代码片段!

Integer count=Integer.MAX_VALUE; // 2147483647
System.out.println(String.format("count is %d",++count));

在这种情况下,输出将2147483648这显然是溢出,如前面的示例所示。

从Java 8开始,数学类提供了一组运算(decrementExact,addExact,multiplyExact等),用于针对数字溢出/下溢的“检查”算术运算。

要触发溢出异常,我们需要使用Math.incrementExact ,它返回递增 1 的参数,如果结果溢出 int,则抛出异常

Integer count=Integer.MAX_VALUE; // 2147483647
Math.incrementExact(count);

我们开始了,例外情况是:

Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.incrementExact(Math.java:964)
at Main.main(Main.java:12)

JavaScript

在 JavaScript 中,如果我们增加一个数字的最大值,我们也不会有溢出异常,并且在撰写本文时,除非您编写自定义函数来达到此目标,否则无法检测到数字溢出异常。

Let's prove that.

let counter=Number.MAX_VALUE;
console.log(++counter);

In the previous snippet we are incrementing by one the maximum value of Number represented by the constant Number.MAX_VALUE. The output of this snippet is 1.7976931348623157e+308 the original value of the variable counter (so the increment has non effect).

But how detect an numeric overflow/underflow JavaScript?

在algotech.solutions 的这篇文章中,有一些很好的算术考虑因素,可以实现自定义函数来检测数字溢出/下溢。

在 Python 3 中,整数没有固定大小(本文解释了它们的结构),唯一的限制是可用内存。因此,在内存可用之前,以下代码永远不会停止。

from time import sleep

count=int(0)
step = int(10**10000)
while(True):
    count+=step
    sleep(0.2)

如果我们想对整数的维度有更多的控制,我们可以使用NumPy

import sys
import numpy as np

count=np.int64(sys.maxsize)
count+=1

在这里,我们提供了例外:
RuntimeWarning: overflow encountered in long_scalars
count+=1
-9223372036854775808

结论

检测数字溢出/下溢昂贵的,因此许多编程语言的默认行为是忽略它,让程序员决定是选中还是取消选中算术运算。



这篇关于#、Java、JavaScript 和 Python 中的数字溢出管理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程