0

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?

BlueKhakis
  • 293
  • 1
  • 8
  • Hi @user202729, thanks for your answer, I'm afraid I'm not familiar with much programming terminology, could you explain what that means? – BlueKhakis Feb 12 '21 at 03:13
  • Integer divided by integer gives integer, discarding remainder. – Steve Summit Feb 12 '21 at 03:13
  • There's https://stackoverflow.com/questions/27674295/why-do-we-separately-cast-to-float-in-an-integer-division or [c - Why did my float get truncated? - Stack Overflow](https://stackoverflow.com/questions/35097935/why-did-my-float-get-truncated) but it's for C. – user202729 Feb 12 '21 at 03:13
  • Does this answer your question? [truncated integer division removal](https://stackoverflow.com/questions/35407084/truncated-integer-division-removal) – user202729 Feb 12 '21 at 03:14
  • You need `380. / 3`, or `380 / 3.`, or `(float)380 / 3`, or `380 / (float)3`. – Steve Summit Feb 12 '21 at 03:14
  • Or alternatively [casting - Store division of integers in float value C++ - Stack Overflow](https://stackoverflow.com/questions/11762680/store-division-of-integers-in-float-value-c) . – user202729 Feb 12 '21 at 03:15
  • Okay, thanks guys- so I think I now understand I just need to make one of my number a `float` and then everything should run smoothly. – BlueKhakis Feb 12 '21 at 03:17

1 Answers1

2

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
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256