shell小數進行比較

參考:http://renylai.blogbus.com/logs/27962818.html

第一種:

#!/bin/bash
#
read -p 'Input a number:' nu
if [ $nu \> 100.00 ]; then
    echo "success..."
else
    echo "failure..."
fi

執行結果對比:

[root@localhost data]# ./test.sh 
Input a number:1
failure...
[root@localhost data]# ./test.sh 
Input a number:1.1
failure...
[root@localhost data]# ./test.sh 
Input a number:10.1
failure...
[root@localhost data]# ./test.sh 
Input a number:11.1
success...
[root@localhost data]# ./test.sh 
Input a number:100.1
success...
[root@localhost data]# ./test.sh 
Input a number:2
success...

第二種和第三種:

#!/bin/bash
#
read -p "input number:" nu
a=`echo "$nu > 100.0"|bc`        #第二種
b=`expr $nu \> 100.0`            #第三種
echo -e "a:$a\tb:$b\tc:$c"

測試結果(正確返回1,錯誤返回0):

[root@244 sh]# ./test.sh   
input number:1
a:0     b:0
[root@244 sh]# ./test.sh 
input number:1.1
a:0     b:1
[root@244 sh]# ./test.sh 
input number:11.1
a:0     b:1
[root@244 sh]# ./test.sh 
input number:10.1
a:0     b:1
[root@244 sh]# ./test.sh 
input number:100.1
a:1     b:1
[root@244 sh]# ./test.sh 
input number:2
a:0     b:1

個人總結(假設小數A與小數B對比,A和B均大於1):

    第一種:

        1.首先對比小數點左邊的數字,只要有一個數字比另外一個數字大,那就是大的數;

        2.如果A小數點左邊的數字都小於或者等於B,那麼不管A小數點右邊的數字是否大於B,A都是小於B的。

    第二種:

        跟整數比較一樣。

    第三種(假設小數A與小數B比較,A和B均大於1):

        A與B對比時,去除小數點,從左自右按順序一一對比,只要A其中一位大於B,那麼A就大於B。

如有錯誤,請指出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章