阿拉伯?dāng)?shù)字轉(zhuǎn)中文數(shù)字腳本。
#!/bin/bash
# 阿拉伯?dāng)?shù)字轉(zhuǎn)換成中文數(shù)字(最大支持到9 9999 9999 9999 9999(17位))胖翰,限制阿拉伯?dāng)?shù)字必須為整數(shù)屋群。
# 設(shè)置一個 num2cn 函數(shù)咕别,阿拉伯?dāng)?shù)字轉(zhuǎn)中文數(shù)字刃唤。
num2cn() {
# 如果沒有傳入?yún)?shù)辜羊,則退出該函數(shù)而非腳本嘶窄,這個錯誤代碼糖赔。如果執(zhí)行該函數(shù)之后還執(zhí)行其他命令則該錯誤代碼無法通過 $? 查詢到战虏。
[ -z ${1} ] && echo "未輸入?yún)?shù)拣宰,退出!" && return 1
# 判斷你輸入的是否為一個整數(shù)烦感,非整數(shù)時(shí)退出該函數(shù)巡社。
echo "${1}" | grep '[^0-9]' &>/dev/null && echo "你輸入的不是一個整數(shù)(${1}), 退出!" && return 2
num=${1}
# 定義 num_cn_array 數(shù)組手趣,0 位對應(yīng) 零 晌该; 1 對應(yīng) 一 2 對應(yīng) 二 ; 以此類推绿渣。
local num_cn_array=(零 一 二 三 四 五 六 七 八 九)
# 定義 num_units_array 數(shù)組朝群,賦予 個位 對應(yīng) ""(空) ; 百位 對應(yīng) 百 中符; 千位 對應(yīng) 千 姜胖;以此類推。
local num_units_array=("" 十 百 千 萬 十 百 千 億 十 百 千 兆 十 百 千 京)
# 統(tǒng)計(jì)輸入的數(shù)字有多少位淀散,用于下面的循環(huán)右莱,有多少位循環(huán)多少次蚜锨。
char_length=$(expr length ${num}) ; [ ${char_length} -gt 17 ] && echo "輸入的數(shù)字太大,超過17位慢蜓,退出亚再!" && return 3
# 定義變量(a=0)用于循環(huán)取輸入輸入數(shù)字的第N位數(shù)字。
local a=0
for ((i=${char_length};i>=1;i--))
do
# 循環(huán)一次變量的值加一晨抡,取數(shù)字從左邊(最高位)開始第N位數(shù)字氛悬。
let a++
# 因?yàn)閿?shù)組是從零開始的而i是從1開始的,所以變量(i)的值減一耘柱。便于后面取出第N位對應(yīng)的數(shù)字單位如捅,從最高位開始到個位("")。
local num_units_temp=$((i - 1))
# 取出 $num 第 $a 位值的數(shù)字賦予變量(num_temp)帆谍,從最高位位開始到個位伪朽。
local num_temp=$(echo $num | cut -c $a)
# 把 num_cn_array 數(shù)組的第 $num_temp 位的值 和 num_units_array 數(shù)組的第 $num_units_temp 位的值 組合到一起賦予給變量(num_cn_temp)轴咱。
local num_cn_temp=${num_cn_array[$num_temp]}${num_units_array[num_units_temp]}
# 每循環(huán)一次汛蝙,把 $num_cn_temp_2 的值和 $num_cn_temp 的值組合到一起賦予該變量 num_cn_temp_2 。 因?yàn)槭菑母呶婚_始的所以 num_cn_temp_2 在前朴肺,num_cn_temp 在后窖剑。
local num_cn_temp_2=${num_cn_temp_2}${num_cn_temp}
unset num_cn_temp
done
num_cn=${num_cn_temp_2}
echo "你輸入的阿拉伯?dāng)?shù)字:${num} 對應(yīng)的中文數(shù)字為: ${num_cn} 。"
}
# 測試
num2cn 99999999999999999
while true
do
read -p "請輸入整數(shù), (如需退出輸入 \"bye\" 戈稿。):" test_num
[ "${test_num}" == "bye" ] && exit 0
num2cn $test_num
done
注:該腳本有缺陷,當(dāng)數(shù)字中有0時(shí)可能會出現(xiàn)歧義西土。
[root@10 ~]# sh shdir/test.sh
你輸入的阿拉伯?dāng)?shù)字:99999999999999999 對應(yīng)的中文數(shù)字為: 九京九千九百九十九兆九千九百九十九億九千九百九十九萬九千九百九十九 。
請輸入整數(shù), (如需退出輸入 "bye" 鞍盗。):100
你輸入的阿拉伯?dāng)?shù)字:100 對應(yīng)的中文數(shù)字為: 一百零十零 需了。
請輸入整數(shù), (如需退出輸入 "bye" 。):101
你輸入的阿拉伯?dāng)?shù)字:101 對應(yīng)的中文數(shù)字為: 一百零十一 般甲。
請輸入整數(shù), (如需退出輸入 "bye" 肋乍。):bye
[root@10 ~]#
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者