Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is printf not using scientific notation?

Tags:

c

printf

pow

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?

like image 863
Simon. Avatar asked Jan 22 '14 16:01

Simon.


People also ask

What is the problem with printf in C?

The printf functions are implemented using a variable-length argument list. Arguments specified after the format string are passed using their inherent data type. This can cause problems when the format specification expects a data object of a different type than was passed.

Can you use scientific notation in C?

Use %E Format Specifier to Print Numbers in Scientific Notation. Scientific notation for numbers is widely used to represent huge and small values with concise universal form. Namely, each number is represented with a single before the decimal point and power of 10s.

How do you print a float in scientific notation?

`e' This prints a number in scientific (exponential) notation. For example, printf "%4.3e", 1950 prints `1.950e+03', with a total of four significant figures of which three follow the decimal point. The `4.3' are modifiers, discussed below. `f' This prints a number in floating point notation.

What is exponential format in C?

Exponential notation produced by printf() always uses a single digit before the . and an exponent ( e+01 here) representing the power of 10 by which to multiply the number. It is a notation commonly used in the scientific community: 30.12 is the same as 3.012e1 or 3.012e+01 0.0012 is the same as 1.2e-3.


2 Answers

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.

like image 132
Sergey Kalinichenko Avatar answered Oct 19 '22 15:10

Sergey Kalinichenko


Have you tried:

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

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

like image 22
abelenky Avatar answered Oct 19 '22 13:10

abelenky