在计算 13 的阶乘的迭代中,它开始产生无效结果。我已经完全按照教科书中的方式输入了它,但是我得到的输出与书中列出的不同。我的编译器是 Dev C++,它设置为 C99 标准。编译器中是否有某些关闭的设置会导致 unsigned long long int 格式不正确或没有适当的最大值? 13岁!它打印出 1932053504。
#include <stdio.h>
//prototype for factorial function
unsigned long long int factorial(unsigned int number);
int main(void){
unsigned int i; //counter for for-loop
//during each iteration call factorial and print result
for( i = 0; i <= 21; ++i){
printf("%u! = %11u\n", i, factorial(i));
}
}
unsigned long long int factorial(unsigned int number){
if(number <= 1){
return 1;
}
else{ //recursive step
return(number * factorial(number - 1));
}
}
最佳答案
我认为您的说明符中有错字。我想你的意思是 ll
而不是 11
。您正在将 unsigned long long
传递给它,因此它需要是
printf("%u! = %llu\n", i, factorial(i));
这是打开(并注意)编译器警告的另一个原因。我的编译器立即告诉我问题出在哪里。
test.c:11:35: warning: format specifies type 'unsigned int' but the argument has type 'unsigned long long' [-Wformat]
printf("%u! = %11u\n", i, factorial(i));
~~~~ ^~~~~~~~~~~~
%11llu
1 warning generated.
你得到的答案是未定义行为的结果,但你的机器是小端,有 32 位整数,13! = 6227020800 > 2^32 = 4294967296 和 6227020800 % 4294967296 = 1932053504 可能是您得到该答案的原因。
关于c - 为什么我的查找 21 以内阶乘的 C 程序从 13 的阶乘开始产生无效结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21820062/