bc 命令

时间:2023-03-09 20:15:00
bc 命令

bc命令是一种支持任意精度的交互执行的计算器语言。是Linux简单的计算器,能进行进制转换与计算。能转换的进制包括十六进制、十进制、八进制、二进制等。可以使用的运算符号包括(+)加法、(-)减法、(*)乘法、(/)除法、(^)指数、(%)余数

语法(选项)

-i:强制进入交互式模式;
-l:定义使用的标准数学库;
-w:对POSIX bc的扩展给出警告信息;
-q:不打印正常的GNU bc环境信息;
-v:显示指令版本信息;
-h:显示指令的帮助信息。

例子

执行浮点运算和一些高级函数:

[root@study ~]# echo "1.1234*5" | bc
5.6170

设定小数精确度

[root@study ~]# echo "scale=3;10/3" | bc
3.333

参数scale=3是将bc输出结果的小数位设置为3位

进制转换

[root@study ~]# vim obase.sh
1 #!/bin/bash
2
3 abc=255
4 echo "obase=2;$abc" | bc # 将十进制转换为二进制
5
6 def=11110000
7 echo "obase=10;ibase=2;$def" | bc # 将二进制转换为十进制
[root@study ~]# . obase.sh
11111111
240

bc --help

[root@study ~]# bc --help
usage: bc [options] [file ...]
-h --help print this usage and exit
-i --interactive force interactive mode
-l --mathlib use the predefined math routines
-q --quiet don't print initial banner
-s --standard non-standard bc constructs are errors
-w --warn warn about non-standard bc constructs
-v --version print version information and exit
[root@study ~]#