微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

体重指数计算器在Bash壳牌

我正在尝试使用Linux中的Bash shell来创build一个脚本来计算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"

如何获得一系列文件中具有最大差异的两个文件

如何在bash中压缩不包括绝对path的目录的文件

Linux从设备本身运行的脚本中卸载一个设备

SSH命令通过bash脚本

从grep输出删除字符

你几乎在那里,你只需要另一个let :

let bmi=$total_weight/$total_height

备择方案

在shell中有多种方法来获得算术上下文。 首选的标准方法是$(( ))语法:

total_weight=$(( $weight * 703 ))

这和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

没有更多的let 。

您也可以直接使用(( ))语法。

(( 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或其他编程语言。

为什么要打扰变数? 如果你不介意使用本地(整数)数学,这是你从let得到的同样的东西:

echo "Your BMI is $(( (weight * 703) / (height * height) ))"

…或者,使用awk进行更准确的计算:

awk -v weight="$weight" -v height="$height" 'BEGIN { printf "%fn",((weight * 703) / (height * height)) }'

就像一个指针… Bash不会做浮点数学,只有整数。 所以你的BMI数字将会消失。 如果要使用除法,则应该使用bc来执行数学运算。

例如:

7/3 = 2(不是2.33333333)

7%3 = 1

如果你需要一个非整数的答案,你可以使用bc :

$ weight=160 $ height=70 $ echo "Your BMI is $(bc <<< "scale=3; ($weight * 703) / ($height * $height)")" Your BMI is 22.955 $

scale=3; 告诉bc输出到3个小数位。 根据你的需要改变这个。

我会用这个bc 。 scale变量表示答案中的小数位数:

bmi=$(bc <<< "scale=2; $total_weight/$total_height")

或者,可以使用-l加载标准的数学库,该库将scale设置为20:

bmi=$(bc -l <<< "$total_weight/$total_height")

awk总是一个选项:

bmi=$(awk -vw="$total_weight" -vh="$total_height" 'BEGIN { print w/h }')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐