bash 如何在bash中做幂
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3888754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do exponentiation in bash
提问by user458553
I try
我试试
echo 10**2
it prints 10**2
. How to make it work?
它打印10**2
。如何使它工作?
回答by codaddict
You can do:
你可以做:
let var=10**2 # sets var to 100.
or even better and recommended way:
甚至更好的推荐方式:
var=$((10**2)) # sets var to 100.
If you just want to print the expression result you can do:
如果您只想打印表达式结果,您可以执行以下操作:
echo $((10**2)) # prints 100.
For large numbers you might want to use the exponentiation operator of bc
as:
对于大数,您可能需要使用bc
as的幂运算符:
bash:$ echo 2^100 | bc
1267650600228229401496703205376
If you want to store the above result in a variable you can again use the $(())
syntax as:
如果要将上述结果存储在变量中,您可以再次使用以下$(())
语法:
var=$((echo 2^100 | bc))
回答by ghostdog74
various ways
各种方式
Bash
重击
x=2
echo $((x**2))
Awk
awk
awk 'BEGIN{print 2**2}'
bc
公元前
echo "2 ^ 2" |bc
dc
直流电
dc -e '2 2 ^ p'
回答by firefly
Actually var=$((echo 2^100 | bc))
doesn't work - bash is trying to do math inside (())
. But a
command line sequence is there instead so it creates an error
实际上var=$((echo 2^100 | bc))
不起作用 - bash 试图在里面做数学运算(())
。但是有一个命令行序列,所以它会产生一个错误
var=$(echo 2^100 | bc)
works as the value is the result of the command line executing inside
()
var=$(echo 2^100 | bc)
值是在内部执行的命令行的结果
()