我在我的Mac上创建了一个bash脚本Armstrong.sh.
这是一个检查数字是一个非常强的数字的函数.
# 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
}
Run Code Online (Sandbox Code Playgroud)
当我写下面的代码时,
armstrong 1 # this is an armstrong number
armstrong 153 # This is an armstrong number
armstrong 24 # This is not an armstrong number
Run Code Online (Sandbox Code Playgroud)
然后它的输出如下,
1 is an armstrong number
153 is an armstrong number
24 is not an armstrong number
Run Code Online (Sandbox Code Playgroud)
直到现在这都很好.
但问题在于此.
当我尝试使用如下循环打印范围内的所有阿姆斯特朗号码时:
# 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
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:
1>如何让循环按预期工作?
2>有什么办法,我可以写代码,而无需使用$temp的armstrong()功能?
就像sum += Math.pow(num%10, 3);在Java中一样?
3>请给我一个更简洁的方法来编写这个armstrong功能.
你的函数使用变量num而不将其声明为局部变量,因此它改变了循环引用的相同shell全局变量,从而重置了循环的状态并阻止它完成.
在功能内部,改变
num=$1
Run Code Online (Sandbox Code Playgroud)
至
local num=$1
Run Code Online (Sandbox Code Playgroud)
...理想情况下,对函数内的所有其他变量执行相同操作,除非您明确希望函数修改全局范围内的变量.
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |