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