我试图在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或其他编程语言.
标签:bash,shell,linux
来源: https://codeday.me/bug/20190629/1322459.html