LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   programming a calculator with bash (https://www.linuxquestions.org/questions/programming-9/programming-a-calculator-with-bash-425427/)

xiekke 03-16-2006 12:18 PM

programming a calculator with bash
 
hi, i am trying to program a calculator,


**************************************************
#!/bin/bash

echo "(($1))"
***************************************************
.. and that is my whole program, works fine wth integers, but with decimals it would show error, can any help with calculating with decimals?

Hko 03-16-2006 12:59 PM

echo "2.101592 + 1.04" | bc

crouse 03-16-2006 03:57 PM

Code:

#!/bin/bash
# bash calculator
echo $1 | bc
exit

or really short
----------------------------
Code:

#!/bin/bash
echo "scale=4; $1" | bc ;exit

save as bashcalc.sh then put an alias into your .bashrc file
Code:

alias calc='sh /home/crouse/scripts/bashcalc.sh'
Quote:

crouse@linux:~> calc 3.555+7.999
11.554
crouse@linux:~>
The "scale=4" allows for division to be carried out to 4 decimal places. You can edit this to whatever length you wish to carry the division to.

xiekke 03-18-2006 08:49 PM

| bc, can you explain that part?

crouse 03-18-2006 11:10 PM

| is the PIPE command . It runs the output of the previous command into the next command. In this case ... bc.

As for bc, direct from the man pages...

Quote:

bc is a language that supports arbitrary precision numbers with inter-
active execution of statements. There are some similarities in the
syntax to the C programming language. A standard math library is
available by command line option. If requested, the math library is
defined before processing any files. bc starts by processing code from
all the files listed on the command line in the order listed. After
all files have been processed, bc reads from the standard input. All
code is executed as it is read. (If a file contains a command to halt
the processor, bc will never read from the standard input.)


All times are GMT -5. The time now is 05:44 PM.