错误的结果是C

时间:2014-05-20 11:48:18

标签: c exp

我想编写一个使用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);
}

1 个答案:

答案 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作为