提高外壳力量

问题描述 投票:21回答:6

您如何将m提高到n的幂?我到处都在搜索。我发现写m**n应该可以,但不能。我正在使用#!/bin/sh

shell exponential
6个回答
22
投票

我会尝试使用计算器bc。有关更多详细信息和示例,请参见http://www.basicallytech.com/blog/index.php?/archives/23-command-line-calculations-using-bc.html

例如

$ echo '6^6' | bc

将6赋予6。


23
投票

使用$ n ** $ m确实有效。也许您没有使用正确的语法来评估数学表达式。这是我在Bash上获得结果的方法:

echo $(($n**$m))

echo $[$n**$m]

这里的方括号并不意味着像if语句中的测试评估器,因此您也可以在不使用空格的情况下使用它们。我个人更喜欢带圆括号的前一种语法。


7
投票

使用bc是一个很好的解决方案。如果要在bash中执行此操作:

$ n=7
$ m=5

$ for ((i=1, pow=n; i<m; i++)); do ((pow *= n)); done
$ echo $pow
16807

$ echo "$n^$m" | bc  # just to verify the answer
16807

4
投票

您可以使用dc。这个

dc -e "2 3 ^ p"

产量

8

1
投票

我的系统管理员未安装dc,因此添加到其他正确答案中,我敢打赌您没有想到这一点-

a=2
b=3
python -c "print ($a**$b)"
>> 8

在bash / shell中工作。


0
投票
#! /bin/bash
echo "Enter the number to be done"
n=2
read m
let P=( $n**$m )
echo "The answer is $p"

回答

Enter the number to be done
3
The answer is 8 
© www.soinside.com 2019 - 2024. All rights reserved.