如何在 bash 中打印用户输入的平方根?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39336725/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:08:39  来源:igfitidea点击:

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

bash

提问by Zero-1729

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.

我最近在 bash 中发现了“bc”,我一直在尝试用它来打印用户输入的平方根。我在下面编写的程序运行成功,但它只打印出“0”而不是用户输入的平方根。

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?

我的代码有什么问题?我错过了什么?

回答by heemayl

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

您的bc命令和命令替换的使用是正确的,问题是您提供了echo $a较早的时间,但未设置。做:

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

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

此外,在扩展变量时,您应该使用变量扩展的常用符号,即$var${var}。我还()sqrt().

回答by scientist_7

Using awkis also possible. For instance, the following example shows 30 decimals of the square root of 98:

awk也可以使用。例如,以下示例显示 98 的平方根的 30 位小数:

awk "BEGIN {printf \"%.30f\n\", sqrt(98)}"

The command above will output 9.899494936611665352188538236078, which you can then store into the avariable.

上面的命令将输出9.899494936611665352188538236078,然后您可以将其存储到a变量中。

回答by arenaq

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

鉴于您在变量中有一个数字var并且您想要该变量的平方根。您还可以使用 awk:

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

or

或者

a=$(echo "$var" | awk '{print sqrt()}')