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

ビット単位の計算と比較をすべて 1 つのステートメントで実行できます。トリックは、結果が探しているものである場合、意図的にゼロ除算エラーを作成することです。もちろん、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 計算内でエスケープするか引用符で囲む必要があります。上記の例では、意図的に両方の手法を示しました。


EDIT:ロジックを逆にして(falseの場合はゼロで割る)、&&演算子を使用することで、ロジックをさらに単純にすることができます。

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 に答える
0
SET LEFT = 1
SET RIGHT = 2
SET /A RESULT = %LEFT% & %RIGHT%

cmd.exeで直接試す場合は、アンパサンド文字(&)を「^」でエスケープしてください。

于 2009-01-13T15:03:53.863 に答える