分类:
2008-03-21 16:51:49
乍看之下,在脚本的范围与能力下处理数(或实数)的运算看起来似乎有点困难。不过仔细想想浮点数也只不过是两个整数的组合。只不过两者间被一个小数点隔开了。如果将我们理解到的这一点放在其他的脚本中,你将可以体验到浮点数的运算速度有多么的惊人。
脚本源代码
#!/bin/sh
# validfloat -- Tests whether a number is a valid floating-point value.
# Note that this script cannot accept scientific (1.304e5) notation.
# To test whether an entered value is a valid floating-point number, we
# need to split the value at the decimal point. We then test the first part
# to see if it's a valid integer, then test the second part to see if it's a
# valid >=0 integer, so -30.5 is valid, but -30.-8 isn't.
. validint # Bourne shell notation to source the validint function
validfloat()
{
fvalue="$1"
if [ ! -z $(echo $fvalue | sed 's/[^.]//g') ] ; then
decimalPart="$(echo $fvalue | cut -d. -f1)"
fractionalPart="$(echo $fvalue | cut -d. -f2)"
if [ ! -z $decimalPart ] ; then
if ! validint "$decimalPart" "" "" ; then
return 1
fi
fi
if [ "${fractionalPart%${fractionalPart#?}}" = "-" ] ; then
echo "Invalid floating-point number: '-' not allowed \
after decimal point" >&2
return 1
fi
if [ "$fractionalPart" != "" ] ; then
if ! validint "$fractionalPart" "0" "" ; then
return 1
fi
fi
if [ "$decimalPart" = "-" -o -z "$decimalPart" ] ; then
if [ -z $fractionalPart ] ; then
echo "Invalid floating-point format." >&2 ; return 1
fi
fi
else
if [ "$fvalue" = "-" ] ; then
echo "Invalid floating-point format." >&2 ; return 1
fi
if ! validint "$fvalue" "" "" ; then
return 1
fi
fi
return 0
}
运行脚本
如果呼叫这个程序的过程中没有任何的错误信息,则系统会返回0, 这个数值的确是一个合法的浮点数。当你要测试之前,可以在上面的程序之后,增加下列几行代码:
if validfloat $1 ; then
echo "$1 is a valid floating-point value"
fi
exit 0
结果
$ validfloat 1234.56
1234.56 is a valid floating-point value
$ validfloat -1234.56
-1234.56 is a valid floating-point value
$ validfloat -.75
-.75 is a valid floating-point value
$ validfloat -11.-12
Invalid floating-point number: '-' not allowed after decimal point
$ validfloat 1.0344e22
Invalid number format! Only digits, no commas, spaces, etc.
*******************************
注意:
如果你在此时看到其他的输出信息的话,这很有可能是之前我们在validint这个函数中增加了几行代码,但加到这个程序时,忘了移除这几行了。请回到validint并移除这几行即可。
*******************************
改进与加強
为了让这个程序能够识別科学记号,我们必须对此程序稍做修改。修改方式并不困难,首先,我们必须先判断数值中有沒有'e' 或'E'的存在,再来将数值分成三段:小数、整数与0的次方。之后我们就可以利用validint来测试。