在 Bash 中使用取模運算子
Nilesh Katuwal
2022年7月18日
Bash
Bash Operator
在本文中,我們將學習如何在 Bash 中使用取模 (%) 運算子。
在 Bash 中使用 Mod (%) 運算子
如果你想計算一個表示式,你需要在 Bash 中使用 expr 命令。必須為每個算術運算呼叫 expr 函式以正確評估從表示式派生的結果。
要對整數執行基本運算,例如加、減、乘、除和取模,我們需要使用符號 expr。
例子:
在我們可以在 shell 中使用它之前,有必要執行 expr 命令來確定模變數的值。因此,我們連續附加了三個 expr 指令,通過利用它們之間的百分比%運算子來確定每次迭代中兩個整數值的模數。
結果,我們得到了三個餘數。
例子:
expr 25 % 2
expr 49 % 3
expr 67 % 7
輸出:
1
1
4
讓我們接受使用者輸入作為引數,以使我們的程式碼更具互動性。此程式碼使用兩個 read 語句來獲取使用者輸入並將其儲存在變數 a 和 b 中;輸入型別必須是整數。
餘數已使用 res 變數和模 % 運算子計算,從而執行 echo 命令。
例子:
read -p "Enter the first number: " a
read -p "Enter the second number: " b
res=$((a%b))
echo "The modulus of $a and $b is: $res"
輸出:
Enter the first number: 8
Enter the second number: 3
The modulus of 8 and 3 is: 2
另一個例子:
for i in {1..10}
do
if [ $(expr $i % 2) != "0" ]; then
echo "$i"
fi
done
上面的程式碼列出了從 1 到 10 的所有奇數。
輸出:
1
3
5
7
9
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe