要求:如果一个整数各位数字之和可以被9整除,那么该数就能被9整除。编写一个脚本,提示用户输入一个整数,然后输出该整数,并告知能够被9整数。
这里只实现了四位数的判断:
#!/bin/bash #chapter_8-8 #trap 'echo "Before executing the line:$LINENO,num=$num,i=$i,sum=$sum" ' DEBUG echo "Please input a integer number:" read num for ((i=3;i>=0;i--)) do let divisor=10**i let temp=num/divisor if [ $temp -ne 0 ] then break fi done echo this is a $((i+1)) bit number. sum=0 case "$i" in 3) let sum=num/10**3+num%10**3/10**2+num%10**2/10+num%10 ;; 2) let sum=num/10**2+num%10**2/10+num%10 ;; 1) let sum=num/10+num%10 ;; 0) let sum=num ;; esac echo sum=$sum if [ $((sum%9)) -eq 0 ] then echo "$num can be divided by 9!" else echo "$num can not be divided by 9!" fi
执行脚本效果:
[root@localhost charpter8]# sh 8-8 Please input a integer number: 4321 this is a 4 bit number. sum=10 4321 can not be divided by 9! [root@localhost charpter8]# sh 8-8 Please input a integer number: 432 this is a 3 bit number. sum=9 432 can be divided by 9! [root@localhost charpter8]# sh 8-8 Please input a integer number: 9333 this is a 4 bit number. sum=18 9333 can be divided by 9! [root@localhost charpter8]#
这能实现不大于4位数的数值。
谁有好的脚本思路可以共享下。