Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c - Why does this float have 2 different values?

When I do this:

float add=0;

int count[] = {3, 2, 1, 3, 1, 2, 3, 3, 1, 2, 1}
for (int i=0; i<11; i++)
    add += 1 / ((float)count+1);

The output is:

4.00000000000000000000

But when I do this:

float add=0;

int count[] = {3, 2, 1, 3, 1, 2, 3, 3, 1, 2, 1}
for (int i=0; i<11; i++)
    add += 1.0 / ((float)count+1);

The output is:

3.99999976158142089844

When I need to turn an int into a float, I either add (float) in front or let it do arithmetic with a decimal such as a / 1.0. Is there any difference?

Edit: Adding the desired behaviour.

The reason is that afterwards, I need a result that adds add to another int variable for an int output. However, when I do it the second way, the int uses 3 instead of 4 so I would like to know what is the difference between the first and second code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code isn't C, but this is:

#include <stdio.h>

int main ()
{
        float add = 0;
        int count[] = { 3, 2, 1, 3, 1, 2, 3, 3, 1, 2, 1 };
        for (int i = 0; i < 11; i++) {
                add += 1 / ((float) count[i] + 1);
        }
        printf("%f
", add);
        return 0;
}

I've executed this code with add += 1 / ((float) count[i] + 1); and add += 1.0 / ((float) count[i] + 1);.

In both cases, printf("%f ", add); prints 4.000000.

However, when I print each bit of the variable add, it gives me 01000000011111111111111111111111 (3.9999998) and 01000000100000000000000000000000 (4)

As pointed by phuclv, this is because 1.0 is a double, hence the calculation is done with double precision, whereas when using 1, the calculation is done using single precision (because of the cast to float).

If you replace the cast to double in the first equation or if you change 1.0 into 1.0f in the second equation, you'll obtain the same result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...