加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – Bash Shell中的BMI计算器

发布时间:2020-12-13 22:55:49 所属栏目:Linux 来源:网络整理
导读:我试图在 Linux中使用Bash shell创建一个脚本来计算BMI.我知道我只是在做一些愚蠢的事情,但我似乎无法使它发挥作用.它不会做分裂.你能看出我出错的地方吗? #!/bin/bash #============================================================== # Script Name: bm
我试图在 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 bmi=$total_weight/$total_height

备择方案

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

total_weight=$(( $weight * 703 ))

这个和expr(见下文)几乎是唯一可以在POSIX中运行的. (还有$[],但是这个已被弃用,并且大部分都与双parens相同.)

通过将变量声明为整数,可以获得一些语法效率.具有整数属性的参数会导致所有赋值表达式的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或其他编程语言.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读