【发布时间】:2016-10-22 15:10:44
【问题描述】:
(perl 新手) 我有一个计算阶乘的小型 perl 程序。我想使用一个while循环,这样在用户得到结果后,他们会被问到“计算另一个阶乘?Y/N”,然后让 Y 再次运行代码并让 N 结束程序。
这是我的代码:
print"Welcome! Would you like to calculate a factorial? Y/N\n";
$decision = <STDIN>;
while $decision == "Y";
{
print"Enter a positive # more than 0: \n";
$num = <STDIN>;
$fact = 1;
while($num>1)
{
$fact = $fact * $num;
$num $num - 1;
}
print $fact\n;
print"Calculate another factorial? Y/N\n";
$decision = <STDIN>;
}
system("pause");
给我带来麻烦的是在哪里放置 while 循环以及如何使 Y/N 选项起作用。我也不清楚system("pause") 和sleep 功能。我确实知道system("pause") 可以让我的程序正常运行。
【问题讨论】:
-
需要
chomp,而==是一个数字比较——你可能需要eq -
当我运行它时,它会立即自行关闭,尽管
system("pause");看代码你知道为什么会这样吗? -
当我尝试你的代码时,我得到了
Scalar found where operator expected at err.pl line 15, near "$num $num" (Missing operator before $num?) Backslash found where operator expected at err.pl line 18, near "$fact\" (Missing operator before \?) syntax error at err.pl line 5, near "while $decision " syntax error at err.pl line 15, near "$num $num " Execution of err.pl aborted due to compilation errors.,也就是说,Perl 甚至没有机会考虑你的system("pause")行。 -
如前所述,
Enter a positive # more than 0:应该是Enter a non-negative integer:。零是一个完美的 valid 输入,您无需更改任何其他内容即可工作!