0

I have multiplied 34e10 of float datatype with 10 and I got the result as 3400000077824.000000

#include <stdio.h>
int main()
{
    float a=34e10;
    a*=10;
    printf("%f",a);
    return 0;
}

I have also tried by making the 10 as a variable called b of type float and got the same answer

But when I use double as a datatype I get the correct answer as 3400000000000.000000

#include <stdio.h>
int main()
{
    double a=34e10;
    //double b=10;
    a*=10;
    printf("%f",a);
    return 0;
}

Someone please explain the problem to me please

phuclv
  • 37,963
  • 15
  • 156
  • 475
vk16_dev
  • 11
  • 1
  • 3
    The problem is that you didn't read about floating point numbers. As a result you don't have a good sense of what is correct, incorrect or expected. – Cheatah Mar 05 '22 at 11:13
  • 3
    You might count the number of correct digits in your output and compare with the precision you can expect for `float` and `double`. – Gerhardh Mar 05 '22 at 11:13
  • 3
    `3400000077824` has more significant digits than `float` can exactly hold (about 7), and fewer than `double` can hold (about 16). With floating point storage, there is a trade-off between range and accuracy. Between `-FLT_MAX` and `FLT_MAX` there is an infinite number of values, but only about 2^32 of those can be exactly represented. The others are approximate. – Weather Vane Mar 05 '22 at 11:19
  • 1
    @vk16_dev Since `34e11` is not exactly representable as a 32-bit `float`, what value would you expect `a` to have? – chux - Reinstate Monica Mar 05 '22 at 12:11
  • 1
    @WeatherVane "3400000077824 has more significant digits than float can exactly hold" is awkward as a `float` can encode 3400000077824 exactly. I understand your end comment but the lead misdirects. – chux - Reinstate Monica Mar 05 '22 at 12:16
  • @chux-ReinstateMonica you are right, I should have written "`3400000000000` has more significant digits than float can exactly hold." The nearest approximation is `3400000077824`. – Weather Vane Mar 05 '22 at 12:26
  • Maybe a bit clearer: `3400000000000` in binary is `110001011110011111110010101101000000000000`, which has more leading non-zero digits (30) than a `float` can store (23+1). Saying that `float` can hold "about 7 decimal digits" may sound more intuitive but ignores the fact that it actually stores numbers in base 2. – chtz Mar 05 '22 at 15:05

0 Answers0