用于查找数字平方根的Bash脚本(巴比伦方法)

时间:2014-10-14 08:25:07

标签: bash

我写了这段代码来找到给定x数的平方根,但是最后一部分给了我“期望的整数表达式”,我该怎么办? (我是一个shell / bash noob)

  #bin/bash
  2 clear
  3 echo "Hello, we will calculate the square root of a number x"
  4 echo "We're going to use the Babylonian Method"
  5 echo "Give me a valor for x"
  6 read x
  7         if [ $x -lt 0 ]
  8         then
  9         clear
 10         echo "The roots of this number are imaginary"
 11         elif [ $x -eq 0 ]
 12         then
 13         clear
 14         echo "The square root of 0 is 0"
 15   else
 16         echo "Now give me a base b and a vertical height h so that bh=x"
 17        
 18         echo "Give me b"
 19         read b
 20         echo "Give me h"
 21         read h
 22 fi
 23
 24         if [ $b -eq $h ]
 25         then
 26         echo:"b or h are already the square root of h"
 27         else
 28         until [ $b -eq $h ]
 29         do
 30         b=`echo "scale=3; ($b + $h)/2"|bc -l`
 31         h=`echo "scale=3; $x/$b"|bc -l`
 32         done
 33         fi
 34         echo "the square root of x is $b or $h"
 35

1 个答案:

答案 0 :(得分:1)

Bash只能处理整数。这同样适用于[ ... ](检查man test):

INTEGER1 -eq INTEGER2
    INTEGER1 is equal to INTEGER2

为了比较花车,请使用bc,因为您已正确进行计数。