Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在bash中将浮点数舍入到小数点后的3位_Bash_Floating Point_Floating Point Precision_Floating Point Conversion - Fatal编程技术网

如何在bash中将浮点数舍入到小数点后的3位

如何在bash中将浮点数舍入到小数点后的3位,bash,floating-point,floating-point-precision,floating-point-conversion,Bash,Floating Point,Floating Point Precision,Floating Point Conversion,我是一名新的bash学习者。我想打印作为输入的表达式的结果,该表达式在小数点后有3位,如果需要,可以四舍五入。 我可以使用下面的代码,但它不循环。假设我将5+50*3/20+(19*2)/7作为以下代码的输入,则给定的输出为17.928。实际结果是17.92857…。因此,它是截断而不是四舍五入。我想对它进行四舍五入,这意味着输出应该是17.929。我的代码: read a echo "scale = 3; $a" | bc -l 等效的C++代码可以是(在main函数中): float a=

我是一名新的
bash
学习者。我想打印作为输入的表达式的结果,该表达式在小数点后有
3位
,如果需要,可以四舍五入。 我可以使用下面的代码,但它不循环。假设我将
5+50*3/20+(19*2)/7作为以下代码的输入,则给定的输出为
17.928
。实际结果是
17.92857…
。因此,它是截断而不是四舍五入。我想对它进行四舍五入,这意味着输出应该是
17.929
。我的代码:

read a
echo "scale = 3; $a" | bc -l
等效的
C++
代码可以是(在
main
函数中):

float a=5+50*3.0/20.0+(19*2.0)/7.0;
cout您可以使用awk:

awk 'BEGIN{printf "%.3f\n", (5+50*3/20 + (19*2)/7)}'
17.929
%.3f
输出格式将数字四舍五入到3个小数点。

如何

a=`echo "5+50*3/20 + (19*2)/7" | bc -l`
a_rounded=`printf "%.3f" $a`
echo "a         = $a"
echo "a_rounded = $a_rounded"
哪个输出

a         = 17.92857142857142857142
a_rounded = 17.929

尝试使用以下方法: 在这里,bc将提供bash caluculator的功能,-l将读取字符串中的每一个数字,最后我们只在末尾打印三个小数

read num
echo $num | bc -l | xargs printf "%.3f"

我不知道为什么,但我想如果你把这个数字除以1,它就会缩放这个数字
echo“scale=3;$a/1”| bc-l
@ooga,对不起,它不起作用。它对这个字符串起作用。但是如果我将字符串作为输入,如何实现它呢?你可以看到我想做什么。谢谢
read num
echo $num | bc -l | xargs printf "%.3f"