用户最多只能进行8次尝试,如果达到8次,则循环应结束。我刚开始学习Perl,所以它只能是Perl的基本概念。当我尝试运行它时,它不允许我输入任何猜测,并且是一个永无止境的循环。它循环下面的错误。我以为我错过了什么,但不确定是什么。
Use of uninitialized value $counter in numeric le (<=)
Use of uninitialized value $guess in numeric gt (>)
Use of uninitialized value $guess in numeric lt (<)
Use of uninitialized value $guess in concatenation (.)
#!usr/bin/perl
use Modern::Perl;
my ($guess,$target,$counter);
$target = (int rand 100) + 1;
print "Welcome to k Perl Whole Number Guessing Game!\n";
print "Please enter a number between 1 and 100 and I will tell you if the number you're trying to guess\nis higher or lower than your guess. You have up to 8 chances to uncover the number.\n";
my $counter <= 8;
print "Enter guess #$counter: $guess";
while(($counter <= 8) || ($target == $guess))
{
if($guess > $target)
{
print "Your guess, $guess, is too high. Try again.";
}
if($guess < $target)
{
print "Your guess, $guess, is too low. Try again.";
}
}
if($target == $guess)
{
print "Congratulations! You guessed the secret number ($target) in $counter tries!"
}
elsif(($target != $guess) && ($counter > 8))
{
print "I'm sorry, you didnt guess the secret number, which was $target."
}
答案 0 :(得分:4)
您在正确的轨道上,我对您的代码进行了小改动
#!usr/bin/perl
use Modern::Perl;
my ($guess,$target,$try,$counter);
$target = (int rand 100) + 1;
print "Welcome to k Perl Whole Number Guessing Game!\n";
print "
Please enter a number between 1 and 100 and I will tell you
if the number you're trying to guess is higher or lower than
your guess. You have up to 8 chances to uncover the number.
";
$try = $counter = 8;
while( $counter ) {
print "You have left #$counter guesses: ";
$guess = <>;
chomp $guess;
print "Your guess, $guess, is too high. Try again.\n"
if($guess > $target);
print "Your guess, $guess, is too low. Try again.\n"
if($guess < $target);
$counter--;
last if $target == $guess;
}
$counter = $try - $counter;
print "Congratulations! You guessed the secret number ($target) in $counter tries!"
if($target == $guess);
print "I'm sorry, you didnt guess the secret number, which was $target."
if($target != $guess);