在 bc 中使用变量
在这一步,我们将学习如何在 bc
中使用变量,让计算变得更加灵活和强大。bc
计算器允许我们定义变量,并在多个计算中重复使用它们。
在 bc 交互模式中使用变量
首先,让我们探索如何在 bc
交互模式中直接使用变量:
- 以交互模式启动
bc
计算器:
bc
- 定义一个变量并使用它进行计算:
x = 10
x + 5
x * 2
你应该会看到:
15
20
- 你可以定义多个变量并一起使用:
y = 7
x + y
x * y
输出将是:
17
70
- 按
Ctrl+D
或输入 quit
退出交互模式。
创建使用 bc 变量的脚本
现在,让我们创建一个脚本来演示如何在 bc
计算中使用变量:
- 如果你还不在项目目录中,请导航到该目录:
cd ~/project
- 创建一个名为
variable_calc.sh
的新脚本文件:
touch variable_calc.sh
- 使用 nano 编辑器打开该文件:
nano variable_calc.sh
- 在文件中添加以下内容:
#!/bin/zsh
## Script to demonstrate using variables in bc
## Define input values
radius=5
height=10
## Calculate cylinder volume (π * r² * h)
volume=$(echo "scale=2; 3.14159 * $radius * $radius * $height" | bc)
## Calculate cylinder surface area (2π * r² + 2π * r * h)
surface_area=$(echo "scale=2; 2 * 3.14159 * $radius * $radius + 2 * 3.14159 * $radius * $height" | bc)
## Display results
echo "Cylinder properties with radius $radius and height $height:"
echo "Volume: $volume cubic units"
echo "Surface Area: $surface_area square units"
此脚本:
- 为圆柱体的半径和高度定义变量
- 使用公式 π _ r² _ h 计算体积
- 使用公式 2π _ r² + 2π _ r * h 计算表面积
- 以适当的单位显示结果
-
按 Ctrl+O
保存文件,然后按 Enter
,再按 Ctrl+X
退出 nano。
-
使脚本可执行:
chmod +x variable_calc.sh
- 运行脚本:
./variable_calc.sh
你应该会看到类似以下的输出:
Cylinder properties with radius 5 and height 10:
Volume: 785.39 cubic units
Surface Area: 471.23 square units
在 bc 内部使用变量
我们还可以使用多行方式在 bc
内部完全定义和使用变量。让我们创建另一个脚本来演示这一点:
- 创建一个新文件:
nano bc_variables.sh
- 添加以下内容:
#!/bin/zsh
## Script to demonstrate using variables within bc
bc << EOF
scale=2
radius = 5
height = 10
pi = 3.14159
## Calculate cylinder volume
volume = pi * radius^2 * height
print "Volume: ", volume, " cubic units\n"
## Calculate cylinder surface area
surface_area = 2 * pi * radius^2 + 2 * pi * radius * height
print "Surface Area: ", surface_area, " square units\n"
EOF
此脚本:
- 使用“here 文档”(EOF)向
bc
发送多行内容
- 在
bc
内部定义所有变量
- 使用这些变量进行计算
- 使用
bc
中的 print
命令显示结果
- 保存文件,使其可执行并运行:
chmod +x bc_variables.sh
./bc_variables.sh
输出应该与上一个脚本类似,但展示了在 bc
中使用变量的不同方法。