的錯誤是由缺少在[]命令報價:[ "$item" -ne 0 ]
。但是,請勿將[]用於算術表達式。 (()):
while((item!= 0));做...完成
此外,你的阿姆斯特朗數的計算似乎是錯誤的。你爲什麼要立方體?在這種情況下,你需要檢查num是否有三位數字,不是嗎? http://en.wikipedia.org/wiki/Narcissistic_number
假設你真正的意思的「阿姆斯特朗數」的標準定義,這應該工作:
#!/bin/sh -eu
is_armstrong() {
local num digits sum
num="$1"
case "$num" in
# Reject invalid numerals.
(*[^0-9]*|0?*) echo "$num: invalid numeral." >&2; return 1;;
esac
digits=${#num}
sum=0
while ((num > 0)); do
((sum += (num % 10) ** digits))
((num /= 10))
done
((sum == $1))
}
# Prompt the user for a number if none were give on the command line.
if (($# == 0)); then
read -p "Enter a natural number: " num
set -- "$num"
fi
# Process all the numbers.
for num in "[email protected]"; do
num=$((num + 0)) # canonicalize the numeric representation
if is_armstrong "$num"; then
echo "$num is an Amstrong Number"
else
echo "$num is not an Amstrong Number"
fi
done
十分感謝:)這工作。4分鐘去,我會選擇它作爲正確答案:) – 2010-06-16 08:31:39
或者最好(爲了可讀性)使用$(...):rem = $(expr $ item%10) – 2010-06-16 08:31:53