bash - 具有浮点类型的数学多整数

标签 bash

在 bash 中,我尝试使用整数和 float 进行数学运算以获得整数结果。下面的代码片段不起作用:

x=25
y=0.2
z=$((x*y))
echo $x*$y=$z

错误信息是:

sh: line 3: 0.2: syntax error: invalid arithmetic operator (error token is ".2")

如果两个变量都是整数,则工作正常。

如何从 bash 脚本中获取“25*0.2=5”?

最佳答案

将打印输出放在 echo 中的引号中。另外,您的 z=$((x*y)) 将使 z 为空或出现错误:

25*0.2: syntax error: invalid arithmetic operator (error token is ".2")

所以...这是经过测试的代码,可能如下所示:

x=25
y=0.2
z=$(echo $x*$y | bc)
echo "$x*$y=$z"

结果将是这样的:

25*0.2=5.0

注意:我们使用bc命令进行z计算

关于bash - 具有浮点类型的数学多整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44935713/

相关文章:

regex - 查找命令与 'regex' 匹配不工作

linux - bash 变量中的 Bash 脚本

linux - 使用 tar 命令时如何防止覆盖现有文件

linux - 避免 bash 脚本等待用户输入 Enter 键

git - 从 Git : How can I set the directory to work in? 开始

"does not begin with"的正则表达式

linux - 移动文件到不同的目录

linux - 每晚备份和合并备份

windows - 从 Cygwin 批量获取命令结果

linux - Bash ARGS 帮助 - 获取随机错误