0

我想编写一个使用高斯算法计算求幂的程序,但是如果给定输入等 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);
}
4

1 回答 1

2

声明a只要(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,用于

于 2014-05-20T12:01:57.583 回答