我的猜谜游戏程序出了什么问题?

时间:2013-09-18 22:12:29

标签: bash

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

第一个问题是它会不断发布您想要猜测的数字,而且它没有说明文件或目录(我不认为我是在呼唤这些东西)。 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."

提前致谢。

1 个答案:

答案 0 :(得分: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