1

我正在尝试制作一个程序,女巫给用户一个随机的数学问题和答案,但是如果我尝试将运算符存储在我的数组中而不将它们放在字符串中,则会出现错误,但是当我希望程序解决问题时,这会导致问题因为运算符被忽略并且两个数字相加。请帮忙!?!

    #!/usr/bin/perl

    use strict;
    use warnings;

    sub randomNumber  #generates a random number (1-100)
    {
        my $randomNumber = int(rand(100)) + 1;
        return "$randomNumber\n";
    }

    sub operators #randomly chooses a operator
    {
        my @list = ( "+" , "-" ,  "/"  , "*" );
        my $index = rand(@list);
        return $list[$index];
        }

    sub question{   
        my $firstNumber = randomNumber();
        my $operater = operators();
        my $secondNumber = randomNumber();
        print $firstNumber.$operater.$secondNumber."\n";
        print $firstNumber + $operater + $secondNumber;   #this is the problem line
    }

    question();

这是运行时的代码截图:

感谢您的帮助,这是我为未来读者完成的实现:

#!/usr/bin/perl

use strict;
use warnings;

sub randomNumber
{
    my $randomNumber = int(rand(100)) + 1;
    return $randomNumber;
}

sub randomOperator
{
    my @operators = ( "+" , "-" ,  "/"  , "*" );
    my $index = rand(@operators);
    return $operators[$index];
    }

sub question{   
    my $firstNumber = randomNumber();
    my $operator = randomOperator();
    my $secondNumber = randomNumber();
    print "$firstNumber $operator $secondNumber =";
    my $userAnswer = <STDIN>;
    my $trueAnswer = eval "$firstNumber $operator $secondNumber";  #gets answer
    if ($userAnswer == $trueAnswer)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

print question(); 
4

2 回答 2

4

三加星号是什么?是的,这没有多大意义,但这是你要求 Perl 做的

看起来您正在尝试生成和执行 Perl 代码,但您会使用.而不是+代替+来连接字符串。然后你仍然需要将代码传递给 Perl 进行编译和执行,这可以使用eval EXPR.

my $code = '$firstNumber' . $operater . '$secondNumber';
my $result = eval($code);

除了生成 Perl 代码,更强大的解决方案是使用调度表。

my %operations = (
   '*' => sub { $_[0] * $_[1] },
   '/' => sub { $_[0] / $_[1] },
   '+' => sub { $_[0] + $_[1] },
   '-' => sub { $_[0] - $_[1] },
);

my $result = $operations{$operater}->($firstNumber, $secondNumber);

笔记:

  • 如果使用调度表,my @list = ...;则变为my @list = keys(%operations);.
  • $operater应该命名为$operator.
  • @list应该命名为@operators.
  • operators应该命名为randomOperator.
于 2013-09-29T17:30:38.210 回答
2
print eval "$firstNumber $operater $secondNumber";

代替

print $firstNumber + $operater + $secondNumber;

eval在处理用户输入时,之前的健全性检查也是一个好主意。

于 2013-09-29T16:56:31.997 回答