0

I am trying to write a simple C program that takes the input from user in metres and prints the output in kilometres, yards and miles rounded to 4 decimal places.

I have used this 1 meter = 0.001 kilometers = 1.094 yards = 0.0006215 miles

When I write this, I get the output as intended:

#include <stdio.h>
int main()
{
   int m;
   float km, y, mi;
   scanf("%d",&m);
   km=(m*0.001);
   y=(m*1.094);
   mi=(m*0.0006215);
   printf("%.4f\n%.4f\n%.4f",km,y,mi);
   return 0;
}

Output:

0.1000

109.4000

0.0622

But, when I write this I get the third output wrong:

#include <stdio.h>
int main()
{
   int m;
   scanf("%d",&m);
   printf("%.4f\n%.4f\n%.4f",(m*0.001),(m*1.094),(m*0.0006215));
   return 0;
}

Output:

0.1000

109.4000

0.0621

Can you please help me find the reason for this difference?


Edit-1

here I gave input 100.

float y=100*0.0006215;
printf("%f",y);

gave output 0.062150

and this

printf("%f",100*0.0006215);

also gave output 0.062150


Edit-2

float y=100*0.0006215;
printf("%.4f",y);

gave output 0.0622

while:

printf("%.4f",100*0.0006215);

gave output 0.0621

whereas in Edit-1 both displayed the same output.

Community
  • 1
  • 1

1 Answers1

1

Please be aware that 0.001 is a double value.

In the first example you assigned the double result to float, truncating its significance, which was then promoted to double when passed to printf.

In the second example, there is no float, the double results are passed directly to printf.

Also, please see Is floating point math broken?.

Community
  • 1
  • 1
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • here I gave input 100: float y=100*0.0006215; printf("%f",y); gave output 0.062150 and this printf("%f",100*0.0006215); also gave output 0.062150 **Then why does using "%.4f" in both the cases gave different answer?** I see that you mentioned there is no float in 2nd example but I see the output containing 6 decimal places, indicating a float rather than a double. Where did I go wrong? – august-rain Nov 06 '16 at 20:17
  • Please see the edit in question for better understanding of my question – august-rain Nov 06 '16 at 20:25
  • Because the numbers are different, and they were rounded differently. – Weather Vane Nov 06 '16 at 20:27
  • Sorry, I still didn't get it. Please see Edit-2. I hope that would be able to explain my question in a better way to you. – august-rain Nov 06 '16 at 20:37
  • If you print with 9 decimal places you get `0.062150002` and `0.062150000` so I would guess that the library code is rounding `5` or less down, and rounding more than `5` up, since when you ask for 4 decimal places, there is that `5xxxx` to be rounded. Please remember that with floating point fractions, you will usually get only an *approximation* of the number, not an *exact* number. That is the relevance of the "broken" link. – Weather Vane Nov 06 '16 at 20:46