2

I'm trying to do this in Ubuntu virtualbox with a shell text:

#!/bin/bash

n1=3.5
n2=3.6
n3=3.7
n=3
let promedio=n1+n2+n3/3
echo $promedio

is about the Average student grade. But then the terminal shows the error:

line 7: let: 3.5: syntax error: invalid arithmetic operator (error token is ".5")

Why? I can't do the + with numbers. What can I do?

I was reading about BC command but I don't know where it goes.

EDIT: I tried adding | BC at the end but is the same error. Also I tried looking at a post about this but they use something different I really don't understand because I'm really new with Ubuntu. They use the $echo or something like that but the code I'm using is different.

damadam
  • 2,873
LeoTwix
  • 35
  • 7

1 Answers1

4

There is no floating point arithmetic operation in bash. So, you can use BC to calculate it:

#!/bin/bash

n1=3.5
n2=3.6
n3=3.7
promedio=`echo $n1 + $n2+ $n3/3 | bc`
echo $promedio   # 3.5 + 3.6 + 1 = 8.1 **This might be not what you want**

BC is a simple command line calculator.

BTW, echo <expression> | bc command will send the calculation of the expression that is obtained using BC to bash.

A little explanation:

  • So, by encapsulating with two `, you are telling that the value promedio is a result that is obtained by command. (In other words, it is called command substitution, see here for more information)

  • By using echo you are saying that the result will be the output of some calculation that is obtained by BC.

  • And there is a logical flaw in these commands, if you use bc like this, it will divide in terms of integer, (3.7/3 = 1), so you should use bc -l command to (3.7/3 = 1.2333...) calculate precisely.

And to divide the sum of these 3 numbers, you should properly do parenthesis:

#!/bin/bash

n1=3.5
n2=3.6
n3=3.7
promedio=`echo "($n1 + $n2+ $n3)/3" | bc -l`
echo $promedio     # (3.5 + 3.6 + 3.7)/3 = 3.60000...
Olimjon
  • 7,522