Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i print square root of user input in bash?

Tags:

bash

I have recently discovered 'bc' in bash, and i have been trying to use it to print out the square root of a user input. The program i wrote below runs successfully, but it only prints out '0' and not the square root of the user input.

Here is the code i wrote:

 #!/data/data/com.termux/files/usr/bin/bash

 echo "input value below"
 read VAR
 echo "square root of $VAR is..."

 echo $((a))                                  
 a=$(bc <<< "scale=0; sqrt(($VAR))")

What is the problem with my code? What am i missing?

like image 604
Zero-1729 Avatar asked Sep 05 '16 19:09

Zero-1729


People also ask

How do you write square root in Linux?

The sqrt() function returns the nonnegative square root of x.

How do I print a value in Bash?

Use the -v flag with printf to assign a shell variable to store the data instead of printing it in standard output. The output prints the stored variable contents. Note: Read our tutorial to learn everything about bash functions.


2 Answers

Your bc command and the use of command substitution is correct, the problem is you have provided the echo $a earlier, when it was unset. Do:

a=$(bc <<< "scale=0; sqrt($VAR)")
echo "$a"

Also while expanding variables, you should use the usual notation for variable expansion which is $var or ${var}. I have also removed a pair of redundant () from sqrt().

like image 166
heemayl Avatar answered Sep 29 '22 06:09

heemayl


Given that you have a number in variable var and you want square root of that variable. You can also use awk:

a=$(awk -v x=$var 'BEGIN{print sqrt(x)}')

or

a=$(echo "$var" | awk '{print sqrt($1)}')
like image 27
arenaq Avatar answered Sep 29 '22 05:09

arenaq