LDP/LDP/guide/docbook/abs-guide/ex61.sh

74 lines
1.3 KiB
Bash
Raw Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
# Arabic number to Roman numeral conversion
2001-09-04 13:27:31 +00:00
# Range: 0 - 200
2001-07-10 14:25:50 +00:00
# It's crude, but it works.
2002-04-01 16:04:17 +00:00
# Extending the range and otherwise improving the script is left as an exercise.
2001-07-10 14:25:50 +00:00
# Usage: roman number-to-convert
LIMIT=200
2001-09-04 13:27:31 +00:00
E_ARG_ERR=65
E_OUT_OF_RANGE=66
2001-07-10 14:25:50 +00:00
if [ -z "$1" ]
then
echo "Usage: `basename $0` number-to-convert"
2001-09-04 13:27:31 +00:00
exit $E_ARG_ERR
2001-07-10 14:25:50 +00:00
fi
num=$1
if [ "$num" -gt $LIMIT ]
then
echo "Out of range!"
2001-09-04 13:27:31 +00:00
exit $E_OUT_OF_RANGE
2001-07-10 14:25:50 +00:00
fi
2001-09-04 13:27:31 +00:00
to_roman () # Must declare function before first call to it.
2001-07-10 14:25:50 +00:00
{
number=$1
factor=$2
rchar=$3
let "remainder = number - factor"
while [ "$remainder" -ge 0 ]
do
echo -n $rchar
let "number -= factor"
let "remainder = number - factor"
done
return $number
2008-07-20 23:16:47 +00:00
# Exercises:
# ---------
# 1) Explain how this function works.
# Hint: division by successive subtraction.
# 2) Extend to range of the function.
# Hint: use "echo" and command-substitution capture.
2001-07-10 14:25:50 +00:00
}
2001-09-04 13:27:31 +00:00
2001-07-10 14:25:50 +00:00
to_roman $num 100 C
num=$?
to_roman $num 90 LXXXX
num=$?
to_roman $num 50 L
num=$?
to_roman $num 40 XL
num=$?
to_roman $num 10 X
num=$?
to_roman $num 9 IX
num=$?
to_roman $num 5 V
num=$?
to_roman $num 4 IV
num=$?
to_roman $num 1 I
2008-07-20 23:16:47 +00:00
# Successive calls to conversion function!
# Is this really necessary??? Can it be simplified?
2001-07-10 14:25:50 +00:00
echo
2008-07-20 23:16:47 +00:00
exit