4.5:语法错误:无效的算术运算符(错误标记为".5")-但是代码仍然可以正常工作,为什么? [英] 4.5: syntax error: invalid arithmetic operator (error token is ".5") - but the code still seems to work, why?

查看:279
本文介绍了4.5:语法错误:无效的算术运算符(错误标记为".5")-但是代码仍然可以正常工作,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用运算符"/"以及数字4.5和2时,我的计算器会生成标题中提到的错误.

My calculator generates the error mentionned in the title when I try to use the operator "/" as well as the numbers 4.5 and 2.

(很像错误状态)这很可能是由于4.5小数点后的原因,但我不知道该如何解决,以及为什么脚本实际上设法在以后给我正确的结果.

This is (just like the error states) most likely due to what's after the decimal point in 4.5 but I don't know how I could fix this and why the script actually manages to give me the correct result afterwards.

感谢您的帮助!

代码:

#!/bin/bash

read -p "Operator: " operator
read -p "First number: " ch1
read -p "Second number: " ch2

case $operator in
 "+") echo "scale=2; $ch1+$ch2" | bc -l;;
 "/") if [[ $ch1 -eq 0 || $ch2 -eq 0 ]]
       then
        echo "Nope..."
       else
        echo "scale=2; $ch1/$ch2" | bc -l
      fi
      ;;
esac

完整输出:

./script2.sh: line 9: [[: 4.5: syntax error: invalid arithmetic operator (error token is ".5")
2.25

推荐答案

尽管产生浮点结果,但是bash不支持除整数以外的其他类型的参数,因此您需要为数学或数学调用诸如bc的外部工具.只能使用整数.

Despite producing floating point results, bash does not support other type of arguments than integers, so you need to rather invoke external tools like bc for your math or stick to integers only.

请参见 bash文档,第"6.5 Shell Arithmetic"部分, :

See bash docs, section "6.5 Shell Arithmetic":

shell允许将算术表达式作为shell扩展之一进行评估,或者通过使用((复合命令,let buildin或声明内置的-i选项.)

The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by using the (( compound command, the let builtin, or the -i option to the declare builtin.

评估是使用固定宽度的整数完成的,尽管会被除以0并标记为错误,但不会检查是否溢出

Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error

这篇关于4.5:语法错误:无效的算术运算符(错误标记为".5")-但是代码仍然可以正常工作,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆