gpt4 book ai didi

perl - 返回长字符串 1 的短阶乘计算器

转载 作者:行者123 更新时间:2023-12-04 07:37:43 28 4
gpt4 key购买 nike

我正在尝试制作一个计算数字阶乘的程序。我对 perl 不是很熟悉,所以我想我缺少一些语法规则。

当我输入 5 时,程序应该返回 120。相反,它返回了几十个 1。当我尝试其他数字时,我仍然会得到 1,但会出现更多或更少的数字,具体取决于我输入的数字更大还是更小。

这是我的代码:

print"enter a positive # more than 0: \n";

$num = <STDIN>;
$fact = 1;

while($num>1)
(
$fact = $fact x $num;
$num = $num - 1;
)

print $fact;
system("pause");

这是我在 stack Overflow 上的第一篇帖子,所以我希望我遵守所有发帖规则。

最佳答案

问题是这一行:

$fact = $fact x $num;

x不是 Perl 中的乘法运算符。它用于重复事物。 1 x 5 将生成 "11111"

相反,您需要 *

$fact = $fact * $num;

可以用*=来写。

$fact *= $num;

其他一些问题...

Get used to strict and warnings now .默认情况下,Perl 将允许您在不声明变量的情况下使用它们。它们是全局性的,这很糟糕,原因您稍后会了解到。现在这意味着如果你在变量名中有一个拼写错误,比如 $face Perl 不会告诉你这件事。

循环数字列表最好用 for 循环遍历 range using .. .

# Loop from 1 to $num setting $factor each time.
for my $factor (1..$num) {
$fact *= $factor;
}

不是使用系统调用来暂停程序,而是使用 sleep .

关于perl - 返回长字符串 1 的短阶乘计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40166563/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com