需要Linux Bash腳本的幫助。實質上,運行時腳本要求用戶輸入三組數字,然後計算輸入的數字並找到平均值。Bash - 計算輸入數字的平均值
#!/bin/bash
echo "Enter a number: "
read a
while [ "$a" = $ ]; do
echo "Enter a second set of numbers: "
read b
b=$
if [ b=$ ]
我該說這個錯嗎?
需要Linux Bash腳本的幫助。實質上,運行時腳本要求用戶輸入三組數字,然後計算輸入的數字並找到平均值。Bash - 計算輸入數字的平均值
#!/bin/bash
echo "Enter a number: "
read a
while [ "$a" = $ ]; do
echo "Enter a second set of numbers: "
read b
b=$
if [ b=$ ]
我該說這個錯嗎?
還不確定你想成爲什麼。但我認爲你可以循環3次。然後每次迭代都會得到一組數字,並將它們相加並記錄您擁有的數量。所以像下面的東西。 (注意$號和$款項會自動初始化爲0)
#!/bin/bash
sum=0
numbers=0
for a in {1..3}; do
read -p $'Enter a set of numbers:\n' b
for j in $b; do
[[ $j =~ ^[0-9]+$ ]] || { echo "$j is not a number" >&2 && exit 1; }
((numbers+=1)) && ((sum+=j))
done
done
((numbers==0)) && avg=0 || avg=$(echo "$sum/$numbers" | bc -l)
echo "Sum of inputs = $sum"
echo "Number of inputs = $numbers"
printf "Average input = %.2f\n" $avg
凡例如輸出將
Enter a set of numbers:
1 2 3
Enter a set of numbers:
1 2 3
Enter a set of numbers:
7
Sum of inputs = 19
Number of inputs = 7
Average input = 2.71
如果OP確實需要「三套」,那麼你的代碼是非常好的。如果它是「一組三個數字」,那麼它是過度的。無論哪種方式,你會得到我的投票。 – Floris
謝謝BroSlow的幫助。這正是我需要的。作品非常好用,謝謝! – user3089320
@ user3089320你應該點擊這個答案旁邊的小複選標記來「接受」它,因爲這是你喜歡的。 – Floris
如果我的理解是否正確,下面的代碼會做什麼你問:
#!/bin/bash
echo "Enter three numbers:"
read a b c
sum=$(($a + $b + $c))
count=3
result=$(echo "scale=2; 1.0 * $sum/$count" | bc -l)
echo "The mean of these " $count " values is " $result
注 - 我將count
作爲單獨變量離開,因此您可以輕鬆擴展此代碼。
使用bc
允許浮點運算(不內置於bash中); scale=2
表示「兩位有效數字」。
採樣運行:
Enter three numbers:
3 4 5
The mean of these 3 values is 4.00
弗洛里斯感謝您在試圖幫助我的過程中的持續支持,但非常感謝BroSlow更好地理解了我所要求的 - 我希望沒有難過的感覺! – user3089320
完全沒有 - 你看到我提出了他的答案。我無法弄清楚你在說什麼 - 他很明顯得到了它。 – Floris
測試值:
sum=200232320
total=30
基本取平均值,得到的百分比:
avg=$(echo "$sum/$total" | bc -l)
avg=$(echo "$avg*100" | bc -l)
printf "Average input = %.2f\n" $avg
基本採取平均與容錯得到百分比:
# -- what if sum=0 or greater than total?
if [ $sum -eq 0 ] || [ $sum -gt $total ] ;then
avg=0
else
avg=$(echo "$sum/$total" | bc -l)
avg=$(echo "$avg*100" | bc -l)
fi
printf "Average input = %.2f\n" $avg
基本取平均值,得到的百分比:
result=$(echo "scale=6; 1.0 * $sum/$total*100" | bc -l)
printf "Average input = %.2f\n" $result
基本取平均值,得到的百分比:
result=$(echo "scale=6; 1.0 * $sum/$total*100" | bc -l)
printf "Average input = %.2f\n" $result
基本取平均值,得到的百分比(用寬容:
# -- if sum is greater than total we have a problem add in 1.0 to address div by zero
[[ $sum -gt $total ]] && result=0 || result=$(echo "scale=6; 1.0 * $sum/$total*100" | bc -l)
printf "Average input = %.2f\n" $result
輸出:
./test.sh
Average input = 66.72
Average input = 66.72
Average input = 66.72
Average input = 66.72
你爲什麼問?它不工作?你使用什麼輸入,你的結果是什麼? – Floris
我不確定該從哪裏出發。腳本應該詢問用戶數量,但之後我不確定如何計算平均值。 – user3089320
你讀的第一個數字的目標是什麼?它只是數字列表中的第一個?你希望用戶在數字之間輸入回車嗎?或者,CR是否意味着輸入結束?請說明您希望輸入的內容,以便我們開始提供幫助。 – Floris