c。factorial程序响应的负值超过8 [英] c program of factorial is responding negative values for more than 8

查看:69
本文介绍了c。factorial程序响应的负值超过8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void main()
{
int fact=1,a;
printf("enter number");
scanf("%d",&a);
for(int i=1;i<=a;i++)
{
fact=fact*i;
}
printf("factorial of entered number is %d",fact);
}



如果我输入8,为什么它以负值响应?


If I enter 8, why is it responding with a negative value?

推荐答案

这取决于 int 的大小。您需要使用 unsigned long int ,而不是使用此类型,否则您将浪费一半的 int 值签名表示,而问题不需要否定。



因子增长太快,所以迟早会溢出任何固定大小的整数值,无论多长时间代表是。如果你使用一些动态增长的大整数类型,你会获得更多的价值:

http:// sourceforge。 net / projects / libbigint / [ ^ ],

http://sourceforge.net/projects/ttmath/ [ ^ ],

https://mattmccutchen.net/bigint/ [ ^ ],

https://github.com/technophilis/BigIntegerCPP [ ^ ]。



但是如何来溢出的正面有符号整数对象使它变为负数?这就是整数在内存中的表示方式。请阅读: http://en.wikipedia.org/wiki/Two%27s_complement [ ^ ]。



这是所有软件开发人员都应该理解的东西。



-SA
It depends on the size of int. Instead of using this type, you need to use unsigned long int, otherwise you waste half of the int values for the signed representation while the problem does not require negatives.

Factorial grows too fast, so sooner or later it will overflow any fixed-size integer value, no matter how long the representation is. You get much more values if you use some dynamically growing "big integer" type:
http://sourceforge.net/projects/libbigint/[^],
http://sourceforge.net/projects/ttmath/[^],
https://mattmccutchen.net/bigint/[^],
https://github.com/technophilis/BigIntegerCPP[^].

But how come overflow of the positive signed integer object makes it negative? This is how integers are represented in memory. Please read this: http://en.wikipedia.org/wiki/Two%27s_complement[^].

This is something all software developers should understand very well.

—SA


这篇关于c。factorial程序响应的负值超过8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆