要求:如果一个整数各位数字之和可以被9整除,那么该数就能被9整除。编写一个脚本,提示用户输入一
个整数,然后输出该整数,并告知能够被9整数。
这里只实现了四位数的判断:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
#!/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
|
执行脚本效果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
[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位数的数值。
谁有好的脚本思路可以共享下。
本文转自 marbury 51CTO博客,原文链接:http://blog.51cto.com/magic3/1428603