Why is printf not using scientific notation?

Simon. picture Simon. · Jan 22, 2014 · Viewed 41.6k times · Source

I understand that this is a common problem. However I can't find a solid straight answer.

16 ^ 54 = 1.0531229167e+65 (this is the result I want)

When I use pow(16,54), I get:

105312291668557186697918027683670432318895095400549111254310977536.0

Code is as follows:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

void main(){

   double public;
   double a = 16;
   double b = 54;
   public = (pow(a,b));

   printf("%.21f\n", public);
}

Code executed with:

gcc main.c -lm

What I'm doing wrong?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jan 22, 2014

What am I doing wrong?

Several things:

  • Use %.10e format for scientific notation with printf for a printout with ten digits after the dot,
  • Return an int from your main,
  • Consider not using public to name a variable, on the chance that your program would need to be ported to C++, where public is a keyword.

Here is how you can fix your program:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(){

   double p;
   double a = 16;
   double b = 54;
   p = (pow(a,b));

   printf("%.10e\n", p);
   return 0;
}

Demo on ideone.