linux 中怎么判斷輸入的數(shù)字是否為合理的浮點(diǎn)數(shù),相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

實(shí)現(xiàn)代碼如下:
#!/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
}notice:
1): if [ ! -z $(echo $fvalue | sed 's/[^.]//g') ] 將輸入,以.分成整數(shù)和小數(shù)部分。
2):if [ "${fractionalPart%${fractionalPart#?}}" = "-" ] 判斷小數(shù)點(diǎn)后面如果接‘-'號(hào),這輸出字符不合法
3)接著的一些if語句就是判斷小數(shù)及整數(shù)部分合不合法
4)由于 valiint函數(shù)沒給出,腳本不能完全執(zhí)行,valiint函數(shù)是判斷字符串是否全為數(shù)字.
看完上述內(nèi)容,你們掌握linux 中怎么判斷輸入的數(shù)字是否為合理的浮點(diǎn)數(shù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
當(dāng)前題目:linux中怎么判斷輸入的數(shù)字是否為合理的浮點(diǎn)數(shù)-創(chuàng)新互聯(lián)
網(wǎng)址分享:http://www.chinadenli.net/article32/ieisc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、關(guān)鍵詞優(yōu)化、網(wǎng)站建設(shè)、建站公司、全網(wǎng)營銷推廣、網(wǎng)站維護(hù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容