Why doesn't printf use scientific notation?

I understand that this is a common problem. However, I cannot find the correct direct answer.

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

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

105312291668557186697918027683670432318895095400549111254310977536,0

The 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 am I doing wrong?

+7
c printf pow
source share
3 answers

What am I doing wrong?

A few things:

  • Use the %.10e format for scientific notation with printf to print ten digits after the dot,
  • Return int from main ,
  • Do not use public to designate a variable, provided that your program must be ported to C ++, where public is the keyword.

Here's 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 ideon.

+16
source share

You tried:

 printf("%e\n", public); 

The %e specifier is for scientific notation, as described in the documentation

+6
source share

If you need scientific notation, you need to use the %e format specifier :

 printf("%e\n", public); ^^ 

In addition, public is a C ++ keyword , so it would be nice to avoid this and any other keywords in this code should be portable.

+3
source share

All Articles