我想编写一个使用Gauss算法计算指数的程序,但如果给出输入等base = 2,exp = 50我得到0.0000。
#include<stdio.h>
float fastpower(int a,int b);
main()
{
int base,exp;
printf("Base:\n");
scanf("%d",&base);
printf("Exp:\n");
scanf("%d",&exp);
fastpower(base,exp);
system("pause");
}
float fastpower(int a,int b)
{
double result=1;
while (b>0)
{
if (b%2!=0)
result=result*a;
b=(b/2);
a=a*a;
}
printf("result is %lf\n",result);
}
答案 0 :(得分:2)
将a
声明为 long ( int64 ):
/*
compute a**b
*/
/* double fastpower(double a, int b) is even more better */
double fastpower(long a, int b) { /* double is more natural here: double result */
double result = 1.0;
while (b > 0) {
if (b % 2 != 0)
result *= a;
b /= 2;
a *= a; /* <- a is long to prevent overflow here */
}
/* You'd rather not output in functions */
printf("result is %lf\n", result);
return result; /* do not forget to return the result*/
}
但long
也可以溢出(例如10 ** 50);在这种情况下,使用double
作为