我正在開發一個程式,除了一個部分之外,所有部分都可以正常作業,該部分應該生成一個可被 7 整除的七位亂數。
我知道有與我類似的問題,但我沒有在其中找到我的答案,盡管嘗試過,我自己也只能在某些時候產生這樣的數字。
知道怎么做嗎?
uj5u.com熱心網友回復:
您可以使用模函式(請參閱set /?):
@echo off
setlocal
set "number=%random%%random%%random%%random%%random%%random%%random%"
set "number=%number:~0,7%"
set /a remainder=number %% 7
if %remainder% equ 0 (
echo %number% is a multiple of 7
) else (
echo %number% divided by 7 gives a rest of %remainder%
)
以防萬一,前導零是可以的,甚至是可能的:
@echo off
setlocal
set "number=%random%%random%%random%%random%%random%%random%%random%"
set "number=%number:~-7%"
set /a remainder=7%number% %% 7
if %remainder% equ 0 (
echo %number% is a multiple of 7
) else (
echo %number% divided by 7 gives a rest of %remainder%
)
uj5u.com熱心網友回復:
這是一種稍微不同的方法,它旨在傳播一個以D7七位數字命名的變數,當除以七時,將回傳一個精確的整數:
第一個示例允許0在結果值中使用前導。
Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "D7="
For /L %%G In (0 1 9) Do For %%H In (
%Random:~-1%%Random:~-1%%Random:~-1%%Random:~-1%%Random:~-1%%Random:~-1%
) Do (Set /A D7 = 7%%H%%G %% 7
SetLocal EnableDelayedExpansion & If !D7! Equ 0 (EndLocal
Set "D7=%%H%%G"
GoTo :Next))
:Next
Set D7
Pause
請注意:結果值可能是0000000因為0允許使用前導并且0可以被每個整數整除。
如果您不想使用0Leadership ,則需要進行很小的調整:
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "D7="
For /L %%G In (1 1 9) Do For %%H In (
%Random:~-1%%Random:~-1%%Random:~-1%%Random:~-1%%Random:~-1%%Random:~-1%
) Do (Set /A D7 = %%G%%H %% 7
SetLocal EnableDelayedExpansion & If !D7! Equ 0 (EndLocal
Set "D7=%%G%%H"
GoTo :Next))
:Next
Set D7
Pause
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/392207.html
