Answers:
您可以在Bash中使用比此处显示的其他语法更简单的语法:
#!/bin/bash
read -p "Enter a number " number # read can output the prompt for you.
if (( $number % 5 == 0 )) # no need for brackets
then
echo "Your number is divisible by 5"
else
echo "Your number is not divisible by 5"
fi
if (( 10#$number % 5 == 0 ))
强制$number
解释为以10为底(而不是前导零所隐含的以8为底/八进制)。
如何使用bc
命令:
!/usr/bin/bash
echo “Enter a number”
read number
echo “Enter divisor”
read divisor
remainder=`echo "${number}%${divisor}" | bc`
echo "Remainder: $remainder"
if [ "$remainder" == "0" ] ; then
echo “Your number is divisible by $divisor”
else
echo “Your number is not divisible by $divisor”
fi
expr $number % $divisor
bc
专门研究计算,因此它可以处理33.3%11.1之类的问题,expr
可能会阻塞。
Nagul的答案很好,但仅供参考,您想要的运算是模(或模),运算符通常是%
。
我以不同的方式做到了。检查它是否适合您。
范例1:
num=11;
[ `echo $num/3*3 | bc` -eq $num ] && echo "is divisible" || echo "not divisible"
Output : not divisible
范例2:
num=12;
[ `echo $num/3*3 | bc` -eq $num ] && echo "is divisible" || echo "not divisible"
Output : is divisible
简单的逻辑。
12/3 = 4
4 * 3 = 12->相同的数字
11/3 = 3
3 * 3 = 9->不同的数字
只是出于语法中立的目的,并在这些部分周围添加明显的中缀表示法偏见,我修改了nagul的解决方案以使用dc
。
!/usr/bin/bash
echo “Enter a number”
read number
echo “Enter divisor”
read divisor
remainder=$(echo "${number} ${divisor}%p" | dc)
echo "Remainder: $remainder"
if [ "$remainder" == "0" ]
then
echo “Your number is divisible by $divisor”
else
echo “Your number is not divisible by $divisor”
fi
dc
安装。