新手一枚,怎么解决溢出问题,求高手指点~~
[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也会损失精度。
所以, 这几个的综合作用下,就出来这个奇怪的结果了
[解决办法]
这个办法还能用吧,只不过感觉很奇怪。
#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);