user3488767
user3488767

Reputation:

Wrong result in C

I want to write a program that calculates expontiation using the Gauss' algorithm but if give input etc base=2,exp=50 i get as a result 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);
}

Upvotes: 0

Views: 167

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Declare a as 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*/  
}

But long could do overflow as well (e.g. 10**50); in this case use double for a

Upvotes: 2

Related Questions