主题:新手提问 关于for 循环求积
wszf888 [专家分:10] 发布于 2009-06-24 12:33:00
刚刚学习 C++ 有个问题:
#include <iostream.h>
int main()
{
int a = 1,i;
for (i = 1; i <= 20; i++ )
{
a = a * i++ ;
}
cout<<a<<endl;
return 0;
}
为什么 得出的结果是负数?
我用 VC++ 6.0
为了求 1*2*3*......*20 的积。
回复列表 (共5个回复)
沙发
YaAnn [专家分:1630] 发布于 2009-06-24 13:05:00
是越界了,
int - Is a datatype that holds whole numbers from -2 (31) (-2,147,483,648) through 2 (31) - 1 (2,147,483,647). Storage size is 4 bytes.
用unsigned int应该可以
[code=c]
#include <iostream.h>
int main()
{
unsigned int a = 1;
int i;
for (i = 1; i <= 20; i++ )
{
a = a * i;
}
cout<<a<<endl;
return 0;
}
[/code]
板凳
bruceteen [专家分:42660] 发布于 2009-06-24 15:47:00
1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20 = 2432902008176640000
因此需要 long long(8字节的整型) 才能装得下
#include <iostream>
int main()
{
unsigned long long a = 1;
for( int i=1; i<=20; ++i )
{
a *= i;
}
std::cout << a << std::endl;
return 0;
}
3 楼
YaAnn [专家分:1630] 发布于 2009-06-24 16:46:00
[quote]1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20 = 2432902008176640000
因此需要 long long(8字节的整型) 才能装得下
#include <iostream>
int main()
{
unsigned long long a = 1;
for( int i=1; i<=20; ++i )
{
a *= i;
}
std::cout << a << std::endl;
return 0;
}
[/quote]
嗯,是这样的,谢了
4 楼
wszf888 [专家分:10] 发布于 2009-06-29 17:37:00
谢谢
5 楼
QQ151914528 [专家分:430] 发布于 2009-07-01 10:26:00
[quote]1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20 = 2432902008176640000
因此需要 long long(8字节的整型) 才能装得下
#include <iostream>
int main()
{
unsigned long long a = 1;
for( int i=1; i<=20; ++i )
{
a *= i;
}
std::cout << a << std::endl;
return 0;
}
[/quote]
unsigned long long 这个类型存在么?编译器出现错误:
d:\microsoft visual studio\vc98\include\xstring(614) : error C2159: more than one storage class specified
d:\microsoft visual studio\vc98\include\xstring(615) : error C2146: syntax error : missing ';' before identifier 'wstring'
d:\microsoft visual studio\vc98\include\xstring(615) : error C2937: 'basic_string<unsigned short,struct std::char_traits<unsigned short>,class std::allocator<unsigned short> >' : template-class-id redefined as a global typedef
d:\microsoft visual studio\vc98\include\xstring(615) : error C2244: 'basic_string<unsigned short,struct std::char_traits<unsigned short>,class std::allocator<unsigned short> >' : unable to resolve function overload
d:\microsoft visual studio\vc98\include\xstring(615) : fatal error C1004: unexpected end of file found
我来回复