BlueKhakis
BlueKhakis

Reputation: 303

When printing a float, how can you print decimal places more precisely?

I'm quite new to coding, and I'm having a very basic problem. I've made a program to perform a basic equation and printf the result:

#include <stdio.h>

int main (void)
{
    float f = (380 / 3);
    
    printf("%f\n", f);
}

However, the result I get is 126.000000. How can I make my program print out the decimal places more precisely?

Upvotes: 0

Views: 294

Answers (1)

chux
chux

Reputation: 153456

How can I make my program print out the decimal places more precisely?

Step 1, Use floating point FP math, not integer math.

// float f = (380 / 3);      // int math
// float f = 380.0f / 3.0f;  // float math
double f = 380.0 / 3.0;      // double math

Step 2: Specify a precision more than the default of 6.

int prec = 7;
printf("%.*f\n", pre, f);

... or better, use exponential notation

printf("%.*e\n", FLT_DECIMAL_DIG, f); 

.... or even hexadecimal.

printf("%a\n", f); 

#include <float.h>
#include <stdio.h>

int main(void) {
  double f = 380.0 / 3.0;
  int prec = 7;
  printf("%.*f\n", prec, f);
  printf("%.*e\n", DBL_DECIMAL_DIG, f);
  printf("%a\n", f);
}

Output

126.6666667
1.26666666666666671e+02
0x1.faaaaaaaaaaabp+6

Upvotes: 2

Related Questions