linux计算器shell,linux – Bash Shell中的BMI计算器

这篇博客讨论了一位用户在Linux环境中使用Bash脚本计算BMI时遇到的困难,主要问题是脚本无法正确执行除法操作。文章提供了错误的脚本片段,并给出了修正方案,包括使用let命令、$(())算术运算或者expr命令来计算BMI。同时,指出这些方法不支持浮点计算,如果需要精确的小数结果,应考虑使用bc、awk或其他编程语言。
摘要由CSDN通过智能技术生成

我试图在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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值