用于检查数字是否为 Armstrong 的 BASH 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3051642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:12:59  来源:igfitidea点击:

BASH Script to Check if a number is Armstrong or Not

bashunix

提问by Atif Mohammed Ameenuddin

I was writing a script to check if a number is Armstrong or not. This is my Code

我正在写一个脚本来检查一个数字是否是阿姆斯特朗。这是我的代码

echo "Enter Number"
read num
sum=0
item=$num
while [ $item -ne 0 ]
do
rem='expr $item % 10'
cube='expr $rem \* $rem \* $rem'
sum='expr $sum + $cube'
item='expr $item / 10'
done
if [ $sum -eq $num ]
then
echo "$num is an Amstrong Number"
else
echo "$num is not an Amstrong Number"
fi

After I run this script,

在我运行这个脚本之后,

$ ./arm.sh

$ ./arm.sh

I always get these errors

我总是收到这些错误

line 5: [: too many arguments

第 5 行:[: 参数太多

line 12: [: too many arguments

第 12 行:[:参数太多

I am on cygwin.

我在 cygwin 上。

回答by Kilian Foth

Those are straight quotes in your exprcommands. To evaluate an expression, you need to use backquotes:

这些是您的expr命令中的直引号。要评估表达式,您需要使用反引号:

rem=`expr $item % 10`

回答by Mark Edgar

The errors are from missing quotes in the [ ] command: [ "$item" -ne 0 ]. However, do not use [ ] for arithmetic expressions. Instead, use (( )):

错误来自 [ ] 命令中缺少引号: [ "$item" -ne 0 ]。但是,不要将 [ ] 用于算术表达式。相反,使用 (( )):

while ((item != 0)); do ... done

而((项目!= 0));做...完成

Also, your calculation for Armstrong number seems to be wrong. Why are you cubing? You need to check that num has exactly three digits in that case, do you not? http://en.wikipedia.org/wiki/Narcissistic_number

此外,您对阿姆斯特朗数的计算似乎是错误的。你为什么要立方?在这种情况下,您需要检查 num 是否正好是三位数字,不是吗? http://en.wikipedia.org/wiki/Narcissistic_number

Assuming you really meant the standard definition of "Armstrong number", this should work:

假设你真的指的是“阿姆斯壮数”的标准定义,这应该有效:

#!/bin/sh -eu

is_armstrong() {
  local num digits sum
  num=""
  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 == ))
}

# 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 "$@"; 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