コードに問題がありますか? [閉鎖]

コードに問題がありますか? [閉鎖]
#!/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行目に構文エラーがないように0に設定します。

9行には演算がないため、整数結果を得ます。 8行と9行を次にマージします。

mileage=$(echo "scale=4; $mil / $gal" | bc)

これにより、mileage10進数の結果が得られます。

役に立つ操作は行われず、$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"

また、以下の事項もご確認ください。

関連情報