2014-09-30 9 views
0

我試圖設計一個腳本,它給出任何歐元和美分的任意命令行輸入,使用最小數量的音符或硬幣計算更改。該腳本正常工作與數字沒有小數點, 例如:使用十進制數字(KornShell)運行的問題

[[email protected] ]$ ksh my_script.sh 34212 
68 500 euro note/s 
1 200 euro note/s 
1 10 euro note/s 
1 2 euro coin/s 

當我通過一個小數點作爲parametre一個數量的問題開始,我會解釋一下我的代碼是如何工作的第一,所以你可以更好地理解問題,首先我創建一個包含所有不同的音符和硬幣值(500,200等等)的數組,然後遍歷該數組,檢查除法結果(total_euros/note_or_coin_value)大於或等於1.如果是這樣,我使用模數來得到餘數並保存我用過的鈔票/硬幣的數量。如果你不明白我的「精彩」解釋技能,這裏是代碼。

CANT=$1 
RES='' 
vals=(500 200 100 50 20 10 5 2 1 0,50 0,20 0,10 0,05 0,02 0,01) 
flag=1 
i=0 

while [ $flag -eq 1 ]; do 

n=$(expr $CANT/${vals[$i]}) 

if [ $n -ge 1 ]; then  # <- LINE 22 


    if [ ${vals[$i]} -gt 2 ]; then 
     RES=$RES' '$n' '${vals[$i]}' euro note/s\n' 
    else 
     RES=$RES' '$n' '${vals[$i]}' euro coin/s\n' 
    fi 

    CANT=$(expr $CANT % ${vals[$i]}) 
fi 

if [ $CANT -eq 0 ]; then 
    flag=0 
fi 

i=$i+1 

if [ $i -gt 14 ]; then 
    flag=0 
fi 

done 

echo -e $RES 

現在,那爲什麼它完全沒有小數點,但是當它們存在它這樣做:

[[email protected] ejercicios]$ ksh my_script.sh 3421,32 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 
expr: non-numeric argument 
my_script.sh[22]: [: argument expected 

我希望你明白的問題,在先進的感謝。 PS:如果有什麼不清楚只是評論,我會更新! :P

+0

確保'x'在'如果[$ x -eq 0]'是一個整數。另外,請進行更正:'if [$ i -gt 14];然後' – 2014-09-30 14:17:15

+0

但我希望它們不必是整數... – Juanpe 2014-09-30 14:21:28

+1

我建議將輸入乘以100並將其作爲整數處理。相應地修改數組'vals'。 – 2014-09-30 14:26:49

回答

3

,如果你想使用一個逗號,您將需要設置LC_NUMERIC:

$ echo $LC_NUMERIC 

$ echo $((1.5 * 2.5)) 
3.75 
$ export LC_NUMERIC=it_IT 
$ echo $((1.5 * 2.5)) 
ksh: 1.5 * 2.5 : arithmetic syntax error 
$ echo $((1,5 * 2,5)) 
3,75 
$ ksh --version 
    version   sh (AT&T Research) 93u+ 2012-08-01 

和expr可以不做浮點運算,在任何情況下

$ expr 1.5 \* 2.5 
expr: non-integer argument 
$ expr 1,5 \* 2,5 
expr: non-integer argument