How to overfill the float?

Working on how to solve Exercise 2.1 with a "C programming language", on which you need to calculate on a local computer a range of different types, such as char, short, int, etc., but also float and double. Everything except float and double, I watch how overflow occurs, and therefore can calculate max / min values. However, on floats this still doesn't work.

So the question is, why does this code print the same value twice? I thought the second line should print inf

 float f = 1.0; printf("%f\n",FLT_MAX); printf("%f\n",FLT_MAX + f); 
+8
c floating-point
source share
2 answers

Try multiplying by 10, and if there is an overflow. The reason it doesn't overflow is the same reason that adding a small float to an already very large float doesn't actually change the value - it's a floating point format, which means that the number of precision digits is limited.

Or, adding at least that the last significant digit is likely to work:

 float f = 3.402823e38f; // FLT_MAX f = f + 0.000001e38f; // this should result in overflow 
+5
source share

The reason it prints the same value twice is because 1.0 too small to add to FLOAT_MAX . A float usually has 24 bits for the mantissa and 8 bits for the exponent. If you have a very high value with an exponent of 127, you will need a mantissa with at least 127 bits to add 1.0 .

As an example, the same problem exists with decimal (and any other) exponential values: If you have a number with 3 significant digits, such as 1.00 * 10 6 you cannot add 1 to it, because it will be 1'000 ' 001, and this requires 6 significant digits.

You can overflow a float by doubling the value repeatedly.

+2
source share

All Articles