【问题标题】:Why doesn't division produce a result in shell programming?为什么除法不会在 shell 编程中产生结果?
【发布时间】:2009-11-30 12:10:37
【问题描述】:

我有一个shell程序,一小部分可以看如下:

count=1000
total=100000
percent=`expr $count/$total`

不能产生除法结果,结果文件中只显示1000/100000。

有什么帮助吗?非常感谢~

【问题讨论】:

  • 你用的是什么shell语言?
  • @Justin:问题是 which shell。 Bash、dash、ash、ksh、csh、zsh 等

标签: shell


【解决方案1】:

需要在'/'符号前后加空格:

percent=`expr $count / $total`

但它是一个整数除法。所以你要么需要先将 $count 乘以 100,要么使用类似 'bc' 的东西。

【讨论】:

    【解决方案2】:

    您应该在要划分的值和 / 运算符之间有空格,如下所示:

    count=1000
    total=100000
    percent=`expr $count / $total`
    #                   ^ ^ - those are important
    

    【讨论】:

      【解决方案3】:

      更好地使用bc:

      percent=$(echo "scale=2; $count/$total" | bc)
      

      【讨论】:

      • 当我按照你的建议使用 bc 时,我得到了以下错误信息,我应该在这个命令中添加什么?为什么终端将生成的 .89 数字识别为新命令?非常感谢!! ./loop_count_reference_frame_no.sh:第 24 行:.89:找不到命令
      • 我明白了,= 和后面的表达式之间不应该有空格。非常感谢!
      【解决方案4】:

      使用 gawk

      count=1000
      total=100000
      result=$(gawk -v c=$count -v t=$total 'BEGIN{print c/t }')
      echo "result is $result"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 2017-06-05
        • 2020-03-24
        • 2021-11-10
        相关资源
        最近更新 更多