Mac에서 Armstrong.sh
이라는 bash 스크립트를 만들었습니다.루프가 예기치 않게 Bash 스크립트에서 무한히 실행됩니다.
숫자를 암스트롱 번호로 확인하는 기능입니다.
# This function works properly
armstrong() {
num=$1 # Making a copy of the received number.
sum=0 # This will store the sum of cubes of each digit from $num
while [ $num -gt 0]; # This loop runs while $num is greater than 0
do
temp=`expr $num % 10` # Extract the last digit of the number
sum=`expr $sum + $temp \* $temp \* $temp` # Cube the last digit and add it to $sum
num=`expr $num/10` # Remove the last digit of the number
done
if [ $sum -eq $1 ]; # If $sum == $1, i.e., If the number is armstrong
then
echo "$1 is an armstrong number" # print the number
else
echo "$1 is not an armstrong number"
fi
}
나는 다음과 같은 코드를 작성
,armstrong 1 # this is an armstrong number
armstrong 153 # This is an armstrong number
armstrong 24 # This is not an armstrong number
는 그 다음이 지금까지 좋았다
1 is an armstrong number
153 is an armstrong number
24 is not an armstrong number
다음과 같이 출력이 있습니다.
그러나 문제이 여기에 있습니다.
# Accept start and end point of the range
echo -n "Enter start = "
read start
echo -n "Enter end = "
read end
# Loop from start to end point and call the armstrong() function
for ((num = $start; num <= $end; num++))
do
armstrong $num # Calling the function.
done
그래서 제 질문은 다음과 같습니다 :이 같은 루프를 사용하여 범위 내에서 모든 암스트롱 번호를 인쇄하려고 할 때
는
1> 어떻게 루프 원하는대로 작업을 어떻게해야합니까?
2>
armstrong()
함수에
$temp
을 사용하지 않고 코드를 작성할 수 있습니까?
Java에서
sum += Math.pow(num%10, 3);
과 똑같습니까?
3> 더 깨끗한 방법으로
armstrong
함수를 작성하십시오.
bash를 목표로하고 있기 때문에, 수학 문맥을 더 많이 사용하는 것을 고려해보십시오.'if ((sum == $ 1))'는'if [ "$ [sum"-eq "$ 1"]'보다 읽기 쉽습니다. –
... 마찬가지로 현대 POSIX sh 문법은'temp = $ ((num % 10))'과'sum = $ ((sum + temp * $ temp * $ temp))'이다; POSIX Bourne을 목표로하지 않는 한 수학에'expr'을 사용할 필요가 없습니다 (요즘은 거의 알려지지 않았습니다). –
쉘 스크립트 btw의 정적 분석을 위해 http://shellcheck.net/ 사용을 고려하십시오. –