#!/bin/bash
Echo “Enter a number”
Read $number
If [$number ] ; then
Echo “Your number is divisible by 5”
Else
Echo “Your number is not divisible by 5”
fi
if [$number] 语句是我不知道如何设置的
答案1
你可以在 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
答案2
不公元前只要是整数运算就需要(浮点运算需要 bc):在 bash 中,(( ))操作符的工作原理类似于表达式。
正如其他人指出的那样,你想要的操作是模数 (%)。
#!/bin/bash
echo "Enter a number"
read number
if [ $(( $number % 5 )) -eq 0 ] ; then
echo "Your number is divisible by 5"
else
echo "Your number is not divisible by 5"
fi
答案3
如何使用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
答案4
我以不同的方式完成了此操作。检查它是否适合您。
例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 --> 不是相同的数字