0

所以是的,我正在为学校做这件事,但我写了大部分剧本。我不知道它发生了什么,可能是语法错误,但它一直在搞砸(或者我这样做)。

第一个问题是它不断发布您试图猜测的数字并且它说没有文件或目录(我不认为我在呼吁这样的事情)。86 是当前的随机数。

./random: line 14: 86: No such file or directory

第二个问题是程序告诉我猜测总是太低(我也可以让它们总是太高)

 I'm thinking of a number between 1 and 100. Your guess:6

./random: line 14: 86: No such file or directory
Sorry, your guess is too low. New guess:87

./random: line 14: 86: No such file or directory
Sorry, your guess is too low. New guess:

这是我的代码:

#!/bin/bash


n1=$[($RANDOM % 100) +1]
guesses=1
echo -n "I'm thinking of a number between 1 and 100. Your guess:"

while read n2; do

if   [ $n2 = $n1 ]; then
break;  
else
echo    
if [ $n2 < $n1 ]; then 
echo -n "Sorry, your guess is too high. New guess:"
elif [ $n2 > $n1]; then
echo -n "Sorry, your guess is too low. New guess:"
fi      
fi
guesses=$((guesses+1))

done
echo
echo "Good job! It took you $guesses guesses to get the right number."

提前致谢。

4

1 回答 1

4

这是上面评论中描述的答案:

#!/bin/bash


n1=$[($RANDOM % 100) +1]
guesses=1
echo -n "I'm thinking of a number between 1 and 100. Your guess:"

while read n2; do

if   [[ $n2 -eq $n1 ]]; then
break;  
else
echo    
if [[ $n2 -gt $n1 ]]; then 
echo -n "Sorry, your guess is too high. New guess:"
elif [[ $n2 -lt $n1 ]]; then
echo -n "Sorry, your guess is too low. New guess:"
fi      
fi
guesses=$((guesses+1))

done
echo
echo "Good job! It took you $guesses guesses to get the right number."

一般来说,您需要注意 bash 给您的错误消息:

./random: line 14: 86: No such file or directory

第 14 行是:

if [ $n2 < $n1 ]; then 

在这种情况下,我们知道 $n1 是 86。所以这意味着脚本正在尝试86像命令一样运行,因此找不到文件错误。为什么 bash 会这样做?那么它可能解释<为重定向而不是大于运算符。所以 if 条件语法有问题。是时候挖掘手册了http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs

于 2013-09-18T22:53:05.250 回答