问题描述
我一直在想可以使用的批处理代码遇到麻烦,但是不要...
I have been having troubles with batch-codes that I would expect to work, but don't...
下面是我写的...
@echo off
cls
:loop
set /p "input=Input a number: "
set /a "number=%input%" 2>nul
REM check if input valid
if "%input%" NEQ "%number%" (
cls
Echo Please Enter a valid number! &Echo.&Echo.
goto :loop
)
Set /a Even=number%%2
if %Even% EQU 0 (
Echo Substituting Even Number in: x / 2
Echo set /p"=(%number%) / 2 = "
set /a answer=number/2
) Else (
Echo Substituting Odd Number in: 3x - 1
<nul set /p"=3(%number%)-1 = "
set /a answer=number*3
set /a answer=answer-1
)
Echo %answer%
Echo.
Echo.
goto :loop
Echo Unexpected Error . . .
pause
Exit
每当我在控制台中输入数字时,它都会像我希望的那样进行数学运算,但是会打印数字-1,并且每次我输入另一个数字时,数字都会变为-2,-3,-4 ,等等.
Whenever I input a number into the console, it does the math, like I want it to, but prints the number -1, and every time i input another number, the number goes to -2, -3, -4, so on.
推荐答案
在@echo off
之后的开头放置一个setlocal enableextensions
,例如
Put a setlocal enableextensions
at the beginning after the @echo off
, e.g.
@echo off
setlocal enableextensions
cls
此外,我认为您还需要使用延迟的变量扩展(通常用!var!
表示),这会将上面的脚本更改为类似以下内容:
Also, I think you would also need to use delayed variable expansion (usually denoted by !var!
), which would change your script above to something like this:
@echo off
setlocal enableextensions enabledelayedexpansion
cls
:loop
set /p "input=Input a number: "
set /a number=!input! 2>nul
REM check if input valid
if "!input!" NEQ "!number!" (
cls
Echo Please Enter a valid number!
Echo.
Echo.
goto :loop
)
REM Make sure that it is an integer put in (just in case)
set /a int=!number! %% 1
if "!input!" NEQ "!int!" (
cls
Echo Please Enter a valid number!
Echo.
Echo.
goto :loop
)
Set /a Even=!number! %% 2
if !Even! EQU 0 (
Echo Substituting Even Number in: x / 2
set /a answer=!number! / 2
) Else (
Echo Substituting Odd Number in: 3x - 1
set /a answer=!number! * 3 - 1
)
Echo !answer!
Echo.
Echo.
goto :loop
我还想指出的是,我还修复了一些其他错误(set /p
在此脚本中根本没有任何用处,尤其是在使用该脚本的地方,而且您还需要模数才能找到甚至/odd).
I also would like to point out that I also fixed a few other bugs (set /p
isn't of any use in this script at all, especially in where it is used, and also you need the modulus to find even/odd).
这篇关于如何在批处理文件中进行数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!