首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

新手一枚,如何解决溢出有关问题,求~

2012-05-20 
新手一枚,怎么解决溢出问题,求高手指点~~[codeC/C++][/code]#includestdio.h#includemath.hint main(

新手一枚,怎么解决溢出问题,求高手指点~~
[code=C/C++][/code]
#include<stdio.h>
#include<math.h>
int main()
{
int x,a, m,n;
scanf("%d %d",&x,&a);
m=pow(x,a);
n=m/1000;
m=m-n*1000;
printf("%d\n",m);
return 0;
}

要表示13^13的最后三位数,为什么运行结果是-371??

[解决办法]
int只有10位数,放不下13^13。
还有 ,pow 是double。转换为int也会损失精度。
所以, 这几个的综合作用下,就出来这个奇怪的结果了
[解决办法]
这个办法还能用吧,只不过感觉很奇怪。

C/C++ code
#include<stdio.h>#include <stdlib.h>#include <string.h>#include<math.h>int main(){    double x,y,m;    int n;    scanf("%lf%lf",&x,&y);    m=pow(x,y);    printf("%0.0lf\n",m);    char LThree[32];    char *a=LThree;    sprintf(LThree,"%0.0lf",m);    if (strlen(LThree)<4)    {        system("pause");        return 1;    }       while (*(a+3)!='\0')    {        a++;    }    *(a+3)='\0';    n=atoi(a);    printf("%d",n);    system("pause");    return 0;}
[解决办法]
unsigned long long CC_pow(unsigned long long a, unsigned long long b)
{
unsigned long long c=1;
for(int i=0; i<b; i++)
{
c *= a;
}
return c;
}

cout<<CC_pow((unsigned long long)13,(unsigned long long)13);

热点排行