[英]Unsigned long int make a variable equal to 0
I have the following code which should compute the factorial of a given number:我有以下代码应该计算给定数字的阶乘:
#include <stdio.h>
int main()
{
unsigned short int n, i;
unsigned long int fact=1;
printf("Give n:");
scanf("%u", &n);
printf("\nfact=%u", fact);
for(i = 1; i <= n; i++)
fact = fact * i;
printf("\n%u!=%u", n, fact);
return 0;
}
I have tried to check what is the problem and found that variable fact is 0. Can somebody explain to me why variable fact is 0 since I have initialized it with 1?我试图检查是什么问题,发现变量 fact 是 0。有人可以向我解释为什么变量 fact 是 0,因为我已经用 1 初始化了它? If it have any importance, I use GNU GCC compiler in Codeblocks.
如果它有任何重要性,我在 Codeblocks 中使用 GNU GCC 编译器。
Since you're using GCC, you should be using -Wall
as an option, which tells you exactly what the problem is:由于您使用的是 GCC,您应该使用
-Wall
作为选项,它会准确地告诉您问题是什么:
prog.c: In function ‘main’:
prog.c:9:4: warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 2 has type ‘short unsigned int *’ [-Wformat=]
scanf("%u", &n);
^
You're telling it to read a value into unsigned int
variable, but you're giving a pointer to an unsigned short
, which is smaller, so it overwrites whatever is after n
in the stack frame, causing undefined behavior -- in your case, corrupting fact
.你告诉它把一个值读入
unsigned int
变量,但你给了一个指向unsigned short
的指针,它更小,所以它覆盖了堆栈帧中n
之后的任何内容,导致未定义的行为——在你的情况下,败坏fact
。
Moral: Always use -Wall
to enable warnings, and pay attention to them...道德:总是使用
-Wall
来启用警告,并注意它们......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.