3

我已经尝试过以下方法,但它只是说“&在这个时候是出乎意料的”。

@echo off
:enter-input
echo Please enter a number between 1 and 15:
echo 1 = Selection one
echo 2 = Selection two
echo 4 = Selection three
echo 8 = Selection four
echo x = Quit

set INPUT=
set /P INPUT=Type number: %=%

if "%INPUT%" == "" goto enter-input
if "%INPUT%" == "x" goto end
if "%INPUT%" == "X" goto end

set /A %INPUT%
if %INPUT% & 1 == 1 echo Selection one
if %INPUT% & 2 == 2 echo Selection two
if %INPUT% & 4 == 4 echo Selection three
if %INPUT% & 8 == 8 echo Selection four

echo Done
:end
4

4 回答 4

8

可以在一个语句中完成逐位数学和比较。如果结果是您正在寻找的结果,诀窍是故意创建除以零错误。当然stderr应该重定向到nul,||操作符用来测试错误情况(表示为TRUE)。

这种技术消除了对任何中间变量的需要。

@echo off
:enter-input
set "input="
echo(
echo Please enter a number between 1 and 15:
echo 1 = Selection one
echo 2 = Selection two
echo 4 = Selection three
echo 8 = Selection four
echo x = Quit

set /P INPUT=Type number:

if not defined input goto enter-input
if /i "%input%" == "X" exit /b

2>nul (
  set /a "1/(1-(input&1))" || echo Selection one
  set /a "1/(2-(input&2))" || echo Selection two
  set /a 1/(4-(input^&4^)^) || echo Selection three
  set /a 1/(8-(input^&8^)^) || echo Selection four
)
pause
goto enter-input

&接受的答案从未说明过一些显而易见的事情:在 SET /A 计算中,像and之类的特殊字符)必须被转义或引用。我有意在上面的示例中演示了这两种技术。


编辑:通过反转逻辑(如果为假,则除以零)并使用&&运算符,可以使逻辑更加简单。

2>nul (
  set /a "1/(input&1)" && echo Selection one
  set /a "1/(input&2)" && echo Selection two
  set /a 1/(input^&4^) && echo Selection three
  set /a 1/(input^&8^) && echo Selection four
)
于 2012-06-09T05:13:01.277 回答
5

我找到了一种方法。

@echo off
:enter-input
echo Please enter a number between 1 and 15:
echo 1 = Selection one
echo 2 = Selection two
echo 4 = Selection three
echo 8 = Selection four
echo x = Quit

set /P INPUT=Type number:

if "%INPUT%" == "" goto enter-input
if "%INPUT%" == "x" goto end
if "%INPUT%" == "X" goto end

set /A isOne = "(%INPUT% & 1) / 1"
set /A isTwo = "(%INPUT% & 2) / 2"
set /A isThree = "(%INPUT% & 4) / 4"
set /A isFour = "(%INPUT% & 8) / 8"

if %isOne% == 1 echo Selection one
if %isTwo% == 1 echo Selection two
if %isThree% == 1 echo Selection three
if %isFour% == 1 echo Selection four

echo Done
:end
于 2009-01-13T14:16:47.517 回答
1

对于按位与,请将表达式放在引号中以避免错误,
例如。set /a "48 & 23"

于 2020-04-11T16:15:51.217 回答
0
SET LEFT = 1
SET RIGHT = 2
SET /A RESULT = %LEFT% & %RIGHT%

如果您直接在 cmd.exe 中尝试,请使用 '^' 转义 & 字符。

于 2009-01-13T15:03:53.863 回答