Multiplication on command line terminal

后端 未结 8 1887
有刺的猬
有刺的猬 2020-12-04 08:00

I\'m using a serial terminal to provide input into our lab experiment. I found that using

$ echo \"5X5\"

just returns a string of \"

相关标签:
8条回答
  • 2020-12-04 08:09

    For more advanced and precise math consider using bc(1).

    echo "3 * 2.19" | bc -l 
    6.57
    
    0 讨论(0)
  • 2020-12-04 08:10

    Yes, you can use bash's built-in Arithmetic Expansion $(( )) to do some simple maths

    $ echo "$((5 * 5))"
    25
    

    Check the Shell Arithmetic section in the Bash Reference Manual for a complete list of operators.

    For sake of completeness, as other pointed out, if you need arbitrary precision, bc or dc would be better.

    0 讨论(0)
  • 2020-12-04 08:23

    The classical solution is:

     expr 5 \* 5
    

    Another nice option is:

     echo 5 5\*p | dc
    

    Both of these solutions will only work with integer operands.

    0 讨论(0)
  • 2020-12-04 08:26

    Internal Methods

    Bash supports arithmetic expansion with $(( expression )). For example:

    $ echo $(( 5 * 5 ))
    25
    

    External Methods

    A number of utilities provide arithmetic, including bc and expr.

    $ echo '5 * 5' | /usr/bin/bc
    25
    
    $ /usr/bin/expr 5 \* 5
    25
    
    0 讨论(0)
  • 2020-12-04 08:26

    If you like python and have an option to install a package, you can use this utility that I made.

    # install pythonp
    python -m pip install pythonp
    
    pythonp "5*5"
    25
    
    pythonp "1 / (1+math.exp(0.5))"
    0.3775406687981454
    
    # define a custom function and pass it to another higher-order function
    pythonp "n=10;functools.reduce(lambda x,y:x*y, range(1,n+1))"     
    3628800
    
    0 讨论(0)
  • 2020-12-04 08:30

    I have a simple script I use for this:

    me@mycomputer:~$ cat /usr/local/bin/c

    #!/bin/sh
    
    echo "$*" | sed 's/x/\*/g' | bc -l
    

    It changes x to * since * is a special character in the shell. Use it as follows:

    • c 5x5
    • c 5-4.2 + 1
    • c '(5 + 5) * 30' (you still have to use quotes if the expression contains any parentheses).
    0 讨论(0)
提交回复
热议问题