#!/bin/bash
set -x
count=0
number=0
loops=0
average=0
read -p " Please enter a number between 1 and 100? " number
while [ $count -lt $number ]
done
average=`expr $score / $number`
echo $average
사용자에게 1에서 100 사이의 숫자를 입력하도록 요청하고 토큰 값 -1을 입력한 후 루프를 종료하는 쉘 프로그램을 작성하십시오. 프로그램은 모든 루프 반복 횟수, 총 횟수, 프로그램 종료 후 평균 횟수를 유지해야 합니다.
진술 을 사용해야 할 것 같은데 if
어떻게 해야 할지 잘 모르겠습니다.
답변1
이 작업을 수행하는 더 효율적인 방법이 있을 수 있지만 다음 스크립트가 해당 작업을 수행해야 합니다.
#!/bin/bash
loops=0
sum=0
# Loop forever
while true; do
read -p "Please enter a number between 1 and 100: " input
# Check for the exit condition.
if [[ $input -eq -1 ]]; then
break
fi
# Use a regex to check that input is a one-digit, two-digit or three-digit number and that the input is in [1,100] .
if [[ $input =~ ^[0-9]{1,3}$ && $input -gt 0 && $input -le 100 ]]; then
# Use arithmetic expansion to increment loop counter and add the new input to sum.
((loops++))
((sum += input))
else
echo "Invalid input. Skipping..."
fi
done
# For the edge case where there is no valid input.
if [[ $loops -eq 0 ]]; then
echo "Average undefined - no valid input."
exit
fi
average=$((sum/loops))
echo "Average: $average"
실행 예시:
Please enter a number between 1 and 100: 2
Please enter a number between 1 and 100: 3
Please enter a number between 1 and 100: 4
Please enter a number between 1 and 100: 5
Please enter a number between 1 and 100: 6
Please enter a number between 1 and 100: -1
Average: 4
답변2
귀하의 요청을 올바르게 이해하지 못했습니다. 그래도 최선을 다하려고 노력합니다. 추가 콘텐츠가 필요한 경우 이 답변을 편집할 수 있도록 아래에 의견을 남겨주세요.
쉘 스크립트는 다음과 같습니다.
$ cat sentinel_2.sh
score=0
loops=0
average=0
while :
do
read -p "Please enter a number between 1 and 100 : " number
if ! [ "$number" -eq "$number" ] 2> /dev/null
then
echo "Not integer"
elif [ $number -eq -1 ]
then
echo "You entered -1, program exits"
break
elif [ $number -gt 100 ] || [ $number -lt 1 ]
then
echo "Out of range"
else
loops=`expr $loops + 1`
score=`expr $score + $number`
echo 'iteration= '$loops' and score = '${score}
fi
done
echo 'Final score = ' $score
echo 'Total iterations= ' $loops
if [ $score -eq 0 ] || [ $loops -eq 0 ]
then
echo "score and iteration are needed to calculate average"
else
echo 'Average = Final Score / Total iterations'
average=$(($score / $loops))
echo 'Average is = '${average}
fi
예제 출력:
$ sh sentinel_2.sh
Please enter a number between 1 and 100 : 3
iteration= 1 and score = 3
Please enter a number between 1 and 100 : 5
iteration= 2 and score = 8
Please enter a number between 1 and 100 : 2
iteration= 3 and score = 10
Please enter a number between 1 and 100 : abcd
Not integer
Please enter a number between 1 and 100 : 102
Out of range
Please enter a number between 1 and 100 : 4
iteration= 4 and score = 14
Please enter a number between 1 and 100 : -1
You entered -1, program exits
Final score = 14
Total iterations= 4
Average = Final Score / Total iterations
Average is = 3
부정적인 경우의 출력 예:
$ sh sentinel_2.sh
Please enter a number between 1 and 100 :
Not integer
Please enter a number between 1 and 100 :
Not integer
Please enter a number between 1 and 100 :
Not integer
Please enter a number between 1 and 100 : abc
Not integer
Please enter a number between 1 and 100 : 100
iteration= 1 and score = 100
Please enter a number between 1 and 100 : 102
Out of range
Please enter a number between 1 and 100 : -1
You entered -1, program exits
Final score = 100
Total iterations= 1
Average = Final Score / Total iterations
Average is = 100
$ sh sentinel_2.sh
Please enter a number between 1 and 100 : 0
Out of range
Please enter a number between 1 and 100 : 102
Out of range
Please enter a number between 1 and 100 : abcd
Not integer
Please enter a number between 1 and 100 : -1
You entered -1, program exits
Final score = 0
Total iterations= 0
score and iteration are needed to calculate average
답변3
#!/bin/bash
declare -i num total avg cnt ;
while read -p "Enter a number: " num ; do
[[ "$num" == "" ]] || [[ $num -eq 0 ]] || [[ $num -gt 100 ]] || [[ $num -lt -1 ]] && echo "ERROR: Out of range" && continue;
[ $num -eq -1 ] && break ;
((cnt++));
((total+=$num));
avg=$(($total/$cnt));
done ;
echo "Count: $cnt Total: $total Avg: $avg"
답변4
if
- 문을 사용하는 대신 :
#!/bin/bash
while IFS= read -r -p 'Enter number 1-100: '
do
case $REPLY in
-1)
break
;;
[1-9]|[1-9][0-9]|100)
sum=$(( sum + REPLY ))
nums=$(( nums + 1 ))
;;
*)
printf '%s is not a valid input\n' "$REPLY" >&2
esac
done
printf '\n'
printf 'Sum of %d numbers is %d\n' "$nums" "$sum"
printf 'Avg of %d numbers is %d\n' "$nums" "$(( sum/nums ))"
이는 패턴을 사용하여 [1-9]|[1-9][0-9]|100
유효한 입력(숫자 1-9, 10-99 및 100)을 일치시킵니다. 또한 사용자는 Ctrl+D일반적으로 입력 종료 신호에 사용되는 을 눌러 루프를 종료할 수 있습니다.