【发布时间】:2020-07-04 16:35:03
【问题描述】:
尝试计算 65 的阶乘,得到正确的输出。任何大于 65 的结果都会导致输出 0。令人震惊,因为我使用的是 unsigned long int。有什么不妥?
代码:
#include <stdio.h>
void factorial(int unsigned long);
int main()
{
int unsigned long num, result;
printf("\nEnter number to obtain factorial : ");
scanf("%ld", &num);
factorial(num);
}
void factorial (int unsigned long x)
{
register int unsigned long f = 1;
register int unsigned long i;
for (i=x;i>=1;i--)
f= f*i;
printf("\nFactorial of %lu = %lu\n",x,f);
}
【问题讨论】:
-
虽然 C 允许您编写
int unsigned long,但经验丰富的程序员从不会这样写,而是使用unsigned long或unsigned long int。 -
关于命名的提示:使用单字母变量时,避免使用可能会提示错误类型名称的变量。例如,名称
f可能会导致您将变量视为float。随着您的代码变得更长或更复杂,这些事情变得更加重要。 -
当你计算 65 时,你怎么知道你得到了正确的输出! ?
-
@M.NejatAydin 你说得对,我的代码生成的阶乘 65 的值是 9223372036854775808 ,与实际值相差甚远。
标签: c int long-integer factorial unsigned-integer