使用读取和function计算区域

我打算计算一个圆的面积。

#! /usr/local/bin/bash read -p "Enter a radius: " area () { a=$(( 3 * $REPLY * 2 )) return $a } echo $(area) 

运行但什么都不返回

 $ bash area.sh Enter a radius: 9 

然后通过引用来重构它

 #! /usr/local/bin/bash read -p "Enter a radius: " radius area (radius) { a=$(( 3 * $radius * 2 )) return "$a" } echo "$(area)" 

它仍然无法正常工作。

 bash area.sh Enter a radius: 9 area.sh: line 3: syntax error near unexpected token `radius' area.sh: line 3: `area (radius) {' 

怎么做这样的计算?

bash中的函数没有命名参数。 你做不到:

 area (foo) { ... function area (foo) { ... 

你可以做:

 area () { local radius a # set a local variable that does not leak outside the function radius=$1 # Save the first parameter to local variable a=$(( 3 * radius * 2 )) echo "$a" } 

然后:

 echo "$(area "$REPLY")" # use $REPLY as the first argument 

由于return设置函数的退出状态,而$(area)使用函数的输出。 这些是不同的。

此外,虽然bash不支持浮点运算,但它确实支持取幂:

 $ bash -c 'echo $((3 * 3 ** 2))' 27 

这是一个快速脚本,它接受半径的输入,然后将其提供给area()的函数,然后回显出返回值。 这适用于安装了bc或二进制计算器。

 #!/bin/bash function area(){ circ=$(echo "3.14 * $1^2" | bc) } #Read in radius read -p "Enter a radius: " #Send REPLY to function area $REPLY #Print output echo "Area of a circle is $circ" 

例:

 terrance@terrance-ubuntu:~$ ./circ.bsh Enter a radius: 6 Area of a circle is 113.04