-3

i started learning c. Today, while i am working on a program, i found an interesting thing and i made another small program (similar to my issue) to check it.

#include<stdio.h>
int main(void)
{
    float num1=867.0;
    float num2=.6921;
    printf("sum = %.4f \n",num1+num2);
    return 0;
}

if i run the above program, i am getting 867.6921 as the answer. but if i changed the .4%f to %f the answer is changing to sum = 867.692078. why's the change in the output? Also, is there any way that i can get the answer without using the .4%f?

yash
  • 1,357
  • 2
  • 23
  • 34

2 Answers2

2

but if i changed the .4%f to %f the answer is changing to sum = 867.692078

printf rounds the result to that many digits after the floating point you specified, the default is .6. While rounding, it uses the current floating point rounding mode, the default is round to the nearest.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • that makes sense. thank you so much! i have another question if that's alright. in my program i am trying to convert a string to a floating point number. is there any way of doing the above without `.4%f` since the user doesn't know how many numbers are there after the decimal. – yash Apr 15 '16 at 00:39
  • ...I don't think this is the point of confusion. This is a floating point representability issue. Naively we would expect `867.692100`, but that value is not representable as a `float`. – J... Apr 15 '16 at 00:39
  • @J... the output should be 867.6921 rather than 867.692100. is there any way of getting it? – yash Apr 15 '16 at 00:44
0

The float type has about seven digits of precision (can be anywhere from 6-9 digits). One alternative is to use g instead of f. This fixes the number of precise digits in the number, not just those after the decimal.

  printf("sum = %.7g \n",num1+num2);

This produces output

sum = 867.6921

and will always give seven digits of precision for any input. Number formats would be like :

0.000000E+07
0000000
000000.0
00000.00
0000.000
000.0000

...etc

J...
  • 30,968
  • 6
  • 66
  • 143