Fedora / UNIX中期望的整数表达式

问题描述 投票:0回答:1

[我一直试图找到一个打印斐波那契数列的脚本,但遇到了一些障碍。

1  #!/bin/sh
2  echo "Program to Find Fibonacci Series"
3  echo "How many number of terms to be generated ?"
4  read
5  n=$REPLY
6  echo "Fibonacci Series up to $n terms :"
7  x=0
8  y=1
9  i=2
10  echo "$x"
11  echo "$y"
12  while [ $i -lt $n ] 
13  do
14    i=`expr $i+1`
15    z=`expr $y+$x`
16    echo "$z"
17    x=$y
18    y=$z
19  done
20
21  exit 0

特别是在第12-13行,它继续打印

integer expression expected

在终端中。

任何帮助将不胜感激

bash unix terminal sh fedora
1个回答
0
投票

此人将$(())用于数学/算术上下文。

#!/bin/sh

echo "Program to Find Fibonacci Series"
read -rp "How many number of terms to be generated ? " n

 case $n in
  [!0-9]*) printf 'You entered %s which is not an int, please try again shall we?\n' "$n"  >&2
     exit 1;;
     '') printf "Nothing was given, please try again..."
     exit 1;;
esac

echo "Fibonacci Series up to $n terms :"

x=0 y=1 i=2

printf '%s\n' "$x" "$y"
while [ $i -lt $n ]; do
  i=$((i+1))
  z=$((y+x))
  echo "$z"
  x=$y
  y=$z
done
  • 我添加了case语句以验证用户输入是否确实是一个整数。
  • 我没有更改您的整个代码,我只是更改/修复了给出错误的原因。
  • 添加-r-p以阅读,我不确定-p是否为POSIX,但是-r为。
© www.soinside.com 2019 - 2024. All rights reserved.