16

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?

TryinHard
  • 4,078
  • 3
  • 28
  • 54
Simon.
  • 1,886
  • 5
  • 29
  • 62
  • 1
    So you want scientific notation? – Shafik Yaghmour Jan 22 '14 at 16:09
  • 1
    Also read about the `g` format specifier. –  Aug 07 '17 at 22:10
  • Your code is exhibits UB (*`main()`* returns an *`int`* - not a *`void`* or anything else no matter what appears to 'work' no matter how many times or how many systems it's run on). ...which I see the answer now points out. Good. Anyway UB is bad news but fortunately this one is easy to fix. – Pryftan Oct 15 '19 at 12:39

3 Answers3

33

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
13

Have you tried:

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

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

abelenky
  • 63,815
  • 23
  • 109
  • 159
4

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

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

Also, public is a keyword in C++ and so it would be a good idea to avoid that and any other keywords in case this code needs to be portable.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • 1
    Amusing puns: *public* [is a] *keyword* (and *public* is in the ghastly C++), *keywords* in *case* (also a keyword in both C and C++ and others too). It's a great idea though to write code with C++ names just to prevent the C++ conversions! But you're right that if there is any chance there will be a desire to port it then better not do that. – Pryftan Oct 15 '19 at 12:48