在 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