Trying to calculate radius and area of circle in B

2019-06-23 17:51发布

问题:

I'm trying to write a basic script to calculate the radius and area of a circle, where PI=3.14, and the circumference is given. I am very very new to scripting, and I can't seem to figure this out.

#!/bin/bash
PI=3.14
CIRC=5
RAD=echo "((CIRC/2*PI))" | bc-l
printf "Radius: %.2f" $RAD
AREA=echo "((PI*RAD**2))" | bc-l
printf "Area: %.2f" $AREA

The sum of both equations are not being stored in those variables, and I have no idea why. I hope someone can help explain.

回答1:

Below script would do it :

#!/bin/bash
pi=3.14
circ=5
rad=$( echo "scale=2;$circ / (2 * $pi)" | bc )
printf "Radius: %.2f\n" $rad
area=$( echo "scale=2;$pi * $rad * $rad" | bc )
printf "Area: %.2f\n" $area

Notes

  1. See [ command substitution ].
  2. Never use full uppercase variables in your script as they are usually reserved for the system, check [ this ].
  3. scale with bc controls the precision, check [ this ].


回答2:

  1. Since bc can print strings, there's no need for printf. Nor backticks or $(), or even some of the variables. With bash, the echo can be replaced with <<<:

    #!/bin/bash
    PI=3.14
    CIRC=5
    bc <<< "scale=2; r=$CIRC/(2*$PI)
            print "'"Radius: ", r, "\nArea: ", '"$PI"'*(r^2), "\n"'
    
  2. POSIX shell code version, using a here document:

    #!/bin/sh
    PI=3.14
    CIRC=5
    bc << snip
          scale=2; r=$CIRC/(2*$PI)
          print "Radius: ", r, "\nArea: ", $PI * (r^2), "\n"
    snip
    
  3. Pure bc:

    #!/usr/bin/bc -q
    pi=3.14; circ=5; scale=2; r=circ/(2*pi)
    print "Radius: ", r, "\nArea: ", pi*(r^2), "\n"
    quit
    


标签: linux bash shell