#!/bin/bash
for ((i=1 ;i<=3;i++))
do
echo "Enter gallon used(gal):"
read gal
echo "Enter Miles Obtained(mil):"
read mil
mileage=`echo $mil / $gal |bc`
echo "scale=4; $mileage " | bc
c=`echo $c + $mileage | bc`
echo "$c + $mileage = $c"
echo
done
答案1
你的蓄能器是吗c
?首先将其设置为零,这样第 10 行就不会出现语法错误。
您会得到一个整数结果,因为第 9 行中没有任何操作。将第 8 行和第 9 行合并为
mileage=$(echo "scale=4; $mil / $gal" | bc)
然后mileage
就会得到一个小数结果。
您没有做任何有用的事情$c
,并且在循环后无法打印它。
答案2
#!/usr/bin/env bash
# Above, get the path to BASH from the environment.
# Below, you could just set the total mileage here.
total_mileage=0
# Below, start from zero and count up for the three loops.
for ((i=0; i<3; i++)); do
# Below, use `-n` to prevent the new line.
# It's ok to use descriptive variable names.
# echo -n "Enter gallons used: "
# Below, quote variables.
# read "gallons"
# Using the suggestion for `read` from @roaima :
read -p "Enter gallons used : " "gallons"
# Use a regular expression (regex). Here, a number with optional decimal:
while [[ ! $gallons =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]; do
echo "Please enter a number or [CTRL]+[C] to exit."
read -p "Enter gallons used : " "gallons"
done
# echo -n "Enter miles obtained: "
# read "miles"
# Using the suggestion for `read` from @roaima :
read -p "Enter miles obtained: " "miles"
while [[ ! $miles =~ ^[+-]?[0-9]+\.?[0-9]*$ ]]; do
echo "Please enter a number or [CTRL]+[C] to exit."
read -p "Enter miles obtained: " "miles"
done
# Below, backticks are antiquated.
mileage=$(echo "scale=4; ($miles) / ($gallons)" | bc)
echo "Mileage: $mileage"
total_mileage=$(echo "scale=4; $total_mileage + $mileage" | bc)
done
average_mileage=$(echo "scale=4; ($total_mileage) / ($i)" | bc)
echo "Average mileage is $average_mileage"
也可以看看这些: