一般情況下,我們使用不帶任何參數的bc
命令。
如果需要bc不輸出提示信息,可以加上-q參數:
bc -q
如果要使用強大的數學庫,比如計算三角函數,需要加上-l參數:
bc -q
bc -l
因為bc本身是一個命令解釋器,要退出它只要直接輸入quit回車或者按Ctrl+D終止。
命令行方式使用bc
# 使用管道
[root@localhost centos39]# echo 3 * 4 | bc
(standard_in) 1: parse error
[root@localhost centos39]# echo "3 * 4" | bc
12
[root@localhost centos39]# echo "scale=7; 355/113" | bc
3.1415929
進制轉換
[root@rhel55 ~]# echo "ibase=16; FFFF" | bc # 16進制要大寫
65535
[root@rhel55 ~]# echo "obase=16; 1000" | bc
3E8
寫入文件計算:
[root@rhel55 ~]# cat test.bc
123*321
123/321
scale=4;123/321
[root@rhel55 ~]# cat test.bc | bc
39483
0
.3831
計算三角形面積舉例:
#!/bin/bash
echo -n "Enter base of a triangle : "
read b
echo -n "Enter height of a triangle : "
read h
area=$(echo "scale=2;(1/2) * $b * $h"|bc) echo "Area of a triangle is $area"
#使用:
[root@smsgw academic]# ./area_of_triangle.sh
Enter base of a triangle : 123
Enter height of a triangle : 321
Area of a triangle is 19741.50
使用數學庫:
# 計算100位的圓周率pi值。
[root@web ~]# echo "scale=100; a(1)*4" | bc
Runtime error (func=(main), adr=11): Function a not defined.
[root@web ~]# echo "scale=100; a(1)*4" | bc -l
3.141592653589793238462643383279502884197169399375105820974944592307\
8164062862089986280348253421170676