本文介绍了批处理文件不能处理大量文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于娱乐考虑,我决定尝试编写一个批处理文件来计算 Hailstone序列.但是,我遇到了一些带有大数字的小问题.

For the sake of my own amusement, I decided to try writing a batch file to calculate Hailstone Sequences. However, I ran into a small problem with some large-ish numbers.

首先,代码:

:START
@ECHO OFF
SETLOCAL
SET /P InputVar="Input Number: "
ECHO.
ECHO %InputVar%
SET ItCount=0

:COLLATZ
SET /A ItCount=%ItCount%+1
SET /A Odd=%InputVar%%%2
IF %Odd% EQU 1 (
    SET /A OutputNum=%InputVar%*3+1
) ELSE (
    SET /A OutputNum=%InputVar%/2
)
ECHO %OutputNum%
IF %OutputNum% LSS 1 (
    GOTO ERROR
) ELSE (
    GOTO RECYCLE
)

:ERROR
ECHO.
ECHO ERROR!
GOTO END

:RECYCLE
IF %OutputNum% EQU 1 (
    GOTO FINISH
) ELSE (
    SET InputVar=%OutputNum%
    GOTO COLLATZ
)

:FINISH
ECHO.
ECHO Completed in %ItCount% iterations.

:END
ENDLOCAL
PAUSE

这适用于我测试过的几个数字.但是,当我开始测试一个新的数字时,需要花费数百次迭代才能完成,系统开始返回 negative 输出.有趣的是,负输出最终解析为零.但是,脚本的这种行为完全不是预期的或预期的.

This works for several numbers I've tested. However, when I got around to testing a number that I new would take hundreds of iterations to complete, the system started returning negative outputs. Interestingly, the negative outputs eventually resolved to zero. However, this behavior of the script is not at all expected or intended.

添加错误处理后,这是我为8388607获得的输出.

After adding in the error handling, this is the output I get for 8388607.

根据 Google ,下一个数字应该是2176782334.

According to Google, the next number should have been 2176782334.

这是命令处理器处理大量数字的能力的自然限制吗?在Excel中,类似的操作运行良好-在那里,我能够确定473个迭代中的数量应解析为1.

Is this a natural limitation of the command processor's ability to handle large numbers? Similar operations run fine in Excel - there, I was able to determine the number should have resolved to 1 in 473 iterations.

我正在运行Windows 7 SP1 x64.

I'm running Windows 7 SP1 x64.

推荐答案

2176782334大于可容纳的32位整数. (2 ^ 31-1 = 2,147,483,647).您遇到的是整数溢出(导致负值).

2176782334 is larger than an 32bit integer can hold. (2^31 - 1 = 2,147,483,647). What you are experiencing is integer overflow, (causing negative values).

大多数现代语言的数据类型为long,可让您保存-2 ^ 64到2 ^ 64 -1范围内的整数.甚至还有一些数据类型允许无限精度的整数,例如Java的BigInteger.

Most modern languages have a datatype long that will allow you to hold integers in the range of -2^64 to 2^64 -1. There are even data types to allow infinite precision integers, like Java's BigInteger.

这篇关于批处理文件不能处理大量文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 02:24