Perl 简单的正面或反面游戏
我正在尝试用 Perl 制作一个简单的正面或反面游戏。但无论答案正确与否,它都告诉我我输了。我在这里错过了一些基本的东西吗?任何帮助将不胜感激。
print "Heads or tails?";
$guess = <>;
print "Your guess is ",$guess;
$randNum = int(rand(10));
if ($randNum % 2 ==0){
$answer = "heads";
} else {
$answer = "tails \n";
}
print "The right answer is ", $guess;
$c = $guess eq $answer;
if ($c == 1){
print "you win!";
} else {
print "you lose";
}
Im trying to make a simple heads or tails game in perl. But no matter if the answer is correct or not it tells me i lose. Am i just missing something fundamental here? Any help would be appreciated.
print "Heads or tails?";
$guess = <>;
print "Your guess is ",$guess;
$randNum = int(rand(10));
if ($randNum % 2 ==0){
$answer = "heads";
} else {
$answer = "tails \n";
}
print "The right answer is ", $guess;
$c = $guess eq $answer;
if ($c == 1){
print "you win!";
} else {
print "you lose";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将考虑您答案中的确切字符串,并且您的答案有一半的时间有换行符,并且两次都是您的猜测。另外,您在 1 个答案后还有一个空格。
例如,假设您猜“正面”,那么您的
$guess
字符串将是:您的答案将是以下其中之一
所以让我们比较这些...
如您所见,唯一可能的方法
eq
正确的情况是您猜到了"tails "
,其中包含空格。您需要做的是清理您的输入,并且答案中不要有任何换行符。
例如:
您还可以去除空格并使字符串大小写相同。
另外,请注意,在没有这两个编译指示的情况下编写 Perl 代码会使您的生活变得非常困难,因此请始终包含它们:
This will take into consideration the exact string in your answer, and your answer has a newline half the time, and your guess both times. Also you have a space after 1 answer.
For example, lets say you guess "heads", then your
$guess
string will be:Your answer will be either of these
So lets compare those...
As you can see, the only possible way for
eq
to be true is if you guessed"tails "
, with an included space.What you need to do is to clean up your input, and not have any newlines in your answer.
For example:
You can also strip whitespace and make the string the same case.
Also, note that writing Perl code without these two pragmas make your life excessively hard, so always include them:
当您阅读答案时,您还会得到最后的换行符。在比较之前,您需要将其从输入中删除。您会看到,如果您在输出周围加上引号:
这将从输入中删除所有空格,这在您的情况下应该有意义:
不相关,但可能会让您感到困惑 --- 您
可能在它应该在的地方
最后,永远style,声明变量并始终将其放在脚本的顶部:
When you read the answer, you also get the final newline. You need to remove it from the input before comparing. You'll see that if you put quotes around the output:
This will remove all spaces from the input, which should make sense in your case:
Unrelated, but may confuse you --- you have
where it should probably be
Finally, for good style, declare your variables and always put this at the top of your script: