跳转到内容

Perl 编程/简单示例 2

来自维基教科书,面向开放世界的开放书籍
上一页:简单示例 1 索引 下一页:概念索引

高低:一个用 perl 编写的简单游戏,要求你猜测 1 到 100 之间的数字,并告诉你你的猜测是高了还是低了。

use warnings;
use strict;

$| = 1;

print "Enter number of games to play: ";
chomp(my $Num_Games = <STDIN>);

my $Num_Guesses = 0;
for my $gameno (1 .. $Num_Games) {
	my $number = 1 + int rand 100;
	
	my $guess;
	do {
		print "Enter guess from 1 to 100: ";
		chomp($guess = <STDIN>);
		++$Num_Guesses;
		
		if ($guess < $number) {
			print "Higher!\n";
		} elsif ($guess > $number) {
			print "Lower!\n";
		}
	} until $guess == $number;
	
	print "Correct!\nAverage guesses per game: ",
	$Num_Guesses / $gameno, "\n\n";
}

print "Games played: $Num_Games\n";


上一页:简单示例 1 索引 下一页:概念索引
华夏公益教科书