1

I need to calculate the area of a circle if the user inputs the circumference. This is what I have, but it's not working:

let radius=$circumference/(2*3.1415) 

and

let area=3.1415*$radius*$radius
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • `bash` cannot do floating point arithmetic. Check this [answer](https://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-division-in-bash). – PesaThe Dec 28 '17 at 23:12
  • 1
    Why are you dividing by π to immediately multiply by π? The area of a circle is half of the circumference times the radius (just look at it like a triangle, it's the same formula). – Pascal Cuoq Dec 28 '17 at 23:36

1 Answers1

2

As the comment pointed out, bash won't do floats. I'd try a simple echo+bc solution, but you can use awk and others as well.

radius=$(echo $circumference/\(2*3.1415\) | bc -l)

and

area=$(echo 3.1415*$radius*$radius | bc -l)

not elegant or particularly portable, but it works.

Edit: I created a test.sh file:

#!/bin/bash

circumference=4

radius=$(echo $circumference/\(2*3.1415\) | bc -l)

area=$(echo 3.1415*$radius*$radius | bc -l)

echo $radius $area

and when I do bash test.sh on the terminal I get:

.63663854846410950183 1.27327709692821900365
Vinicius Placco
  • 1,683
  • 2
  • 14
  • 24
  • 2
    It's better to use `$(cmd)` instead of `\`cmd\``, check this [Bash FAQ #82](http://mywiki.wooledge.org/BashFAQ/082). And just a nitpick, you can also use redirection instead of `echo`: `bc -l <<< "3.1415*$radius*$radius"`. – PesaThe Dec 28 '17 at 23:44
  • im getting a syntax error whenever I run the script – BetaCrasher Dec 29 '17 at 02:03
  • Did you just copy/paste the above? Also, are you using `bash`? I'll add a small script to the answer above, and you can try that. – Vinicius Placco Dec 29 '17 at 02:52