剛開始練習 shell 時不是很習慣
BMI 值計算
執行結果:
- 常常不小心行尾加 ; 分號。
- 不然就是=左右加空白。
比方說 m=100 跟 m = 100 是不一樣,看顏色變化就知道。

BMI 值計算
- 運用 read 指令取得 stdin 的值,存到變數,參數 -p 是提示文字。(ex: read -p "你的名字是" your_name)
- 做簡單的加減乘除計算 BMI,雖然要做到加減乘除要利用 expr,可是 expr 只能取到整數,因此改用 echo scale=2...的方式去做。 scale 的值表示要取到小數第幾位。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
read -p "How about your Height(cm)?" height | |
read -p "How about your Weight(kg)?" weight | |
echo "your height is $height cm" | |
echo "your weight is $weight kg" | |
#because i need chage height's cm to m, and 1m = 100cm | |
m=100 | |
height=`echo "scale=2; $height / $m"|bc` | |
BMI=`echo "scale=2; $weight / ($height*$height)" |bc` | |
echo "---------Result---------" | |
echo "your bmi is $BMI" | |
#設定值(set value時)不能有 $ 在前面 | |
#取值(get value)要有 $ | |
#四則運算要使用 expr, +-*/ 左右都要有空白 | |
#不過因為要取到小數點第二位,因此在這裡就不用 expr | |
#所以不用在乎 expr 使用加減乘除運算的規定(ex: +-*/ 左右要空白) | |
echo "below 18.5 | 偏瘦" | |
echo "18.5-24.9 | 標準" | |
echo "25.0-29.9 | 超重" | |
echo "30.0 above | 肥胖" |

沒有留言:
張貼留言
若你看的文章,時間太久遠的問題就別問了,因為我應該也忘了... XD