How can Linux achieve addition, subtraction, multiplication, and division of two numbers?
In Linux, you can use a shell script to perform addition, subtraction, multiplication, and division of two numbers. Below is an example script:
#!/bin/bash
# 输入两个数
read -p "请输入第一个数:" num1
read -p "请输入第二个数:" num2
# 加法运算
sum=$(expr $num1 + $num2)
echo "加法结果为:$sum"
# 减法运算
diff=$(expr $num1 - $num2)
echo "减法结果为:$diff"
# 乘法运算
product=$(expr $num1 \* $num2)
echo "乘法结果为:$product"
# 除法运算
quotient=$(echo "scale=2; $num1 / $num2" | bc)
echo "除法结果为:$quotient"
Save the code above as a script file (for example, calculator.sh), then run the script in the terminal. The script will prompt for input of two numbers and output their addition, subtraction, multiplication, and division results.
Note: In multiplication operations, use the symbol * to represent multiplication to avoid conflicts with wildcards. For division operations, use the bc command for floating-point arithmetic, and set scale=2 to retain two decimal places.