코드에 문제가 있나요? [폐쇄]

코드에 문제가 있나요? [폐쇄]
#!/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)

그러면 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"

또한 다음 사항도 확인하세요.

관련 정보