#!/bin/bash #定義最大公約數和最小公約數 GCD_RESULT="" LCM_RESULT="" #定義一個相加的函數 function sum() { result=$(( num1+num2 )) echo -e "\033[31m 兩個數之和爲$result \033[0m" } #定義一個求最大公約數函數 function divisor() { if [ "$num1" -eq "$num2" ]; then s_great=$num1 s_small=$num2 #export s_great #export s_small fi if [ "$num1" -gt "$num2" ]; then s_great=$num1 s_small=$num2 else s_great=$num2 s_small=$num1 fi i=1 GCD_RESULT=1 greattmp=1 smalltmp=1 LCM_RESULT=1 export GCD_RESULT while [ $i -le "$s_small" ] do greattmp=`expr $s_great % $i` smalltmp=`expr $s_small % $i` if [ ${greattmp} -eq 0 ]; then if [ ${smalltmp} -eq 0 ]; then GCD_RESULT=${i} fi fi i=`expr ${i} + 1` done LCM_RESULT=`expr $s_small / $GCD_RESULT` LCM_RESULT=`expr $LCM_RESULT \* $s_great` #echo -e "\033[31m 兩個數最大公約數爲$s_great \033[0m" } function say() { divisor echo -e "\033[31m 兩個數最大公約數爲$GCD_RESULT \033[0m" } #定義一個求最小公倍數函數 function multiple() { divisor echo -e "\033[31m 兩個數最小公倍數爲$LCM_RESULT \033[0m" } function main() { echo "---------------------------" echo "請輸入你要執行的方法" echo "輸入1:執行相加函數,返回兩數之和" echo "輸入2:執行最大公約數函數,返回兩數最大公約數" echo "輸入3:執行最小公倍數函數,返回兩數最小公倍數" echo "輸入4:退出" read input case $input in 1) sum;; 2) say;; 3) multiple;; 4) exit;; esac } if [ $# != 2 ];then echo "命令格式不對, 命令格式: sh d.sh num1 num2" exit fi #根據返回的狀態判斷輸入是否爲數字 num=`expr $1 + 0 &>/dev/null` if [ $? -ne 0 ];then echo "num1 必須是數字格式" exit fi num=`expr $2 + 0 &>/dev/null` if [ $? -ne 0 ];then echo "num2 必須是數字格式" fi #顯示選擇菜單 while true do num1=$1 num2=$2 main done
shell計算工具源碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.