Float array sum

Hi everyone,

I'm having some trouble with float array.
When i try to get the array sum with float numbers i get this error line 39: soma + 2.34 | bc: syntax error: invalid arithmetic operator (error token is ".34 | bc")

 26 Somar() {
 27 echo "Quantos numeros deseja somar?"
 28 read numeros
 29 vetorSoma[$numeros]=" "
 30 for (( i=0;i<$numeros;i++ ))
 31 do
 32 con=$((con+1))
 33 echo -n "digite o $con� numero: "  
 34 read vetorSoma[$i]
 35 done
 36 
 37 for i in ${vetorSoma[@]}; do
 38 sum=0
 39 soma=$((soma + $i | bc))
 40 done
 41 echo "O resultado foi $soma"
 42 }

when i type int numbers it works great, i just don't know why.
Thx.

You need to printf / echo a string including your numbers and the arithmetic operation (+ possibly other bc commands like "scale") and pipe that to bc .

Your variable soma is not set initially, that will through some error, along with usage of bc as RudiC noticed.

Try :

Somar() { 
echo "Quantos numeros deseja somar?" 
read numeros 
vetorSoma[$numeros]=" " 
for (( i=0;i<$numeros;i++ )) 
do 
con=$((con+1)) 
echo -n "digite o $con� numero: " 
read vetorSoma[$i] 
done 

soma=0 
for i in ${vetorSoma[@]}; do 
soma=$(echo "scale=2;$soma + $i" | bc -l) 
done 
echo "O resultado foi $soma" 
} 

# call Somar
Somar

Thx Mr RudiC and Mr Akshay Hegde.

Now i can store the float values and saw where i went wrong.

Thx.

Note that if you use a 1993 or later ksh, you can just use something like:

soma=0
for i in ${vetorSoma[@]}; do
        soma=$((soma + $i))
done
printf "O resultado foi %.2f\n" "$soma"

Obviously, adjust the number in red above to set the number of digits you want displayed after the decimal point in your results.