linux - Bash Shell 中的 BMI 计算器

标签 linux bash shell

我正在尝试使用 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 数组中,索引将始终具有算术上下文。 (但这在这里并不适用。)

但是,这些方法都不会进行浮点计算,因此您的除法总是会被截断。如果您需要小数值,请使用 bcawk 或其他编程语言。

关于linux - Bash Shell 中的 BMI 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22648240/

相关文章:

cryptography - Linux内核是否支持RSA加密/解密?

c++ - Linux下如何获取磁盘信息?

bash - 通过 Bash shell WSL1 安装 Yarn

bash - tmux Escape 键退出服务器

linux - 如何在Linux中获取被特定进程修改的文件

linux - 在fish shell中定义别名

linux - 如何从文本文件中获取文件路径并在 bash 中执行操作

python - os.getlogin() 和 os.environ 获取用户名的区别

python - 从父 bash 脚本中不可用的 Python 创建环境变量

shell - '\r' : command not found