-5

I want to create a program that use decimal numbers, so I thought I would need to use float types, but I don't understand how these types behave. I made a test:

#include <stdio.h>
#include <float.h>

int     main(void)
{
    float fl;

    fl = 5 - 100000000;
    printf("%f\n", fl);

    fl = FLT_MAX - FLT_MAX * 2;
    printf("%f\n", fl);

    fl = -100000000000000;
    printf("%f\n", fl);

    return 0;
}

Output:

-99999992.000000   // I expected it to be -99999995.000000
-inf               // I expected it to be -340282346638528859811704183484516925440.000000
-100000000376832.000000 // I expected it to be -100000000000000

Why are the results different of my expectations?

EDIT: Thank's to people who don't just downvote my question for some reasons, and actually try to help me. However, what I could learn in this thread doesn't help me understanding why some float variables containing integers (ending with .000000) behaves strangely.

nounoursnoir
  • 671
  • 2
  • 10
  • 25

1 Answers1

-1

I'm not sure, but I have some ideas. In float numbers any number consists of 2 parts: m,p. Any number can be shown as: X = m * 2^p. (m and p - binary. 0< m <1) So, if you try to do some calculations with numbers(X+Y), firstly computer needs to represent X and Y with the same p. Simple example (not like in program, but like people could do the same):

X=0.5, Y=1.45
  0.55+1.45
  0.55 * 10^0 + 0.145 * 10^1
  0.055 * 10^1 + 0.145 * 10^1 (*)
  0.200 * 10^1

BUT. If X and Y has too different p we have some problems in (*) line. m has limited number of digits, so: Ex.:

X = 0.1, Y = 0.000000000000000001
X + Y = 0.100000000000(000001) <- this part didn't fit into m, so
X + Y = 0.1.

Hope you got what I wanted to say

Timofey Kargin
  • 161
  • 4
  • 15
  • thank's for your answer. However i don't undertand this: "Where m and p - binary." – nounoursnoir Jun 03 '17 at 10:01
  • I've edited post. X and Y - just examples. About binaries - in computer m and p stores in binary form. But in my examples I used decimal system for simplification. So, if I wanted to be strict - it should be m*2^p, not m*10^p as in my examples. – Timofey Kargin Jun 03 '17 at 10:04
  • actually, I find using a base 10 more confusing than using the binary base lol – nounoursnoir Jun 03 '17 at 10:32
  • Please refrain from answering such obvious dupes. You can check out the info page for alist of the most frequently questions. Note that dupes of them are not well researched implicitly. – too honest for this site Jun 03 '17 at 11:59
  • Please tell me what question it is a dupe of. To me it is not a dupe. – nounoursnoir Jun 04 '17 at 16:29