0
r=15
phi=3.14
d=30

let area=$r*$r*phi
echo $area

let radius=2*$phi*$d
echo $radius

when i run the code, show error "syntax error: invalid arithmetic operator (error token is ".14"). i haved searched on google relating this problem. the solution use bc (bash calculator). my question is is there other solution?

second condition i change to 22/7 for phi. but the radius result not as expected the area calculation is correct 707 but the radius shoud be 188 not 180.

thx

  • 2
    Possible duplicate of [Trying to calculate radius and area of circle in BASH](http://stackoverflow.com/questions/38428207/trying-to-calculate-radius-and-area-of-circle-in-bash) – Inian Dec 14 '16 at 09:03
  • 2
    Umm @123, circumference is `2 * PI * r` or `PI * d`, not `2 * PI * d`..... (that's kind of the definition of `PI` (the ratio of the *circumference to the diameter*) – David C. Rankin Dec 14 '16 at 09:05
  • @DavidC.Rankin Yeah, i meant that, woops, i was just pointing out it wasn't radius! – 123 Dec 14 '16 at 09:15
  • Happens to me all the time..., unfortunately... – David C. Rankin Dec 14 '16 at 10:27

2 Answers2

1

I would use awk:

circum=$(awk 'BEGIN{print 3.14159*30}')

echo $circum
94.2477

Or, if you want circumference and area in one go:

read circum area < <(awk 'BEGIN{pi=3.14159;r=15;print 2*pi*r,pi*r*r}')

echo $circum $area
94.2477 706.858

Or bc:

circum=$(bc <<< "3.14159*30")

echo $circum
94.24770

Or both in one go with bc:

{ read circum; read area;}  < <(bc <<< "3.14159*30; 3.14159*15*15")

echo $circum $area
94.24770 706.85775

To understand all the shell syntax and jiggery-pokery, run the following two commands on their own to see what they produce:

awk 'BEGIN{pi=3.14159;r=15;print 2*pi*r,pi*r*r}'

bc <<< "3.14159*30; 3.14159*15*15"
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • yeah ok. so the solution use awk, bc and other like the internet says. i wonder there's simple solution instead using like internet says. why awk or bc must use to solved the floating variable not bash it self? –  Dec 14 '16 at 10:32
0

Hum... Did you forget your school days ? When you did divide and multiply with add and minus ?

Division can be made with integers ("/" and "%" in some languages such as bash), as you did at school.

Multiplication is using "+", only. Imagine 3.14 * 12, make them integers, then add a comma somewhere at the end, you will get the result. Or: 3.14/2, make them also integers, easy, you will get divisor and rest. Make it by hand, you will see. No need floating point calculator for that, our fathers did not get floating-point calculators, but were able to calculate PI thousands of years ago.

I just don't get the question maybe : If people do not understand multiply or divide means for me they do not understand add and subtract.

Bruno
  • 580
  • 5
  • 14