我正在尝试使用 Linux 中的 Bash shell 创建一个脚本来计算 BMI。我知道我只是在做一些愚蠢的事情,但我似乎无法让它发挥作用。它不会做除法。你能看出我哪里出错了吗
#!/bin/bash
#==============================================================
# Script Name: bmicalc
# By: mhj
# Date: March 25, 2014
# Purpose: calculates your bmi from your weight & height
#===============================================================
#Get your weight and height
echo -n "What is your weight in pounds? "
read weight
echo -n "What is your height in inches? "
read height
#calculate your bmi
let total_weight=$weight*703
let total_height=$height*$height
bmi=$total_weight/$total_height
echo "Your weight is $weight"
echo "Your height is $height"
echo -n "Your BMI is $bmi"
最佳答案
你快到了,你只需要另一个 let
:
let bmi=$total_weight/$total_height
备选方案
有很多方法可以在 shell 中获得算术上下文。首选的标准方法是 $(( ))
语法:
total_weight=$(( $weight * 703 ))
This 和 expr
(见下文)几乎是唯一可以在 POSIX sh 中工作的。 (还有 $[ ]
,但它已被弃用并且大部分与双括号相同。)
您可以通过将变量声明为整数来提高语法效率。具有 integer 属性的参数导致所有赋值表达式的 RHS 具有算术上下文:
declare -i weight height bmi total_weight total_height
total_weight=weight*703
total_height=height*height
bmi=total_weight/total_height
不再让
。
您也可以直接使用(( ))
语法。
(( total_weight=weight*703 ))
(( total_height=height*height ))
(( bmi=total_weight/total_height ))
最后,expr
只是 shell 中的一个痛点。
total_weight=$(expr $weight '*' 703) # Have to escape the operator symbol or it will glob expand
total_height=$(expr $height '*' $height) # Also there's this crazy subshell
……嗯,但是完整!
最后,在 bash 数组中,索引将始终具有算术上下文。 (但这在这里并不适用。)
但是,这些方法都不会进行浮点计算,因此您的除法总是会被截断。如果您需要小数值,请使用 bc
、awk
或其他编程语言。
关于linux - Bash Shell 中的 BMI 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22648240/