C #: sum of two two-digit numbers

Possible duplicate:
Why is floating point arithmetic in C # odd?

Hey. I have a problem:

43.65+61.11=104.75999999999999

for decimal correctly:

(decimal)43.65+(decimal)61.11=104.76

Why is the result for double incorrect?

+5
source share
7 answers

This question and its answers provide a wealth of information about it. - Difference between decimal, float and double in .NET?

Quote:

  • , " " . , : , . , , .

  • , , , float/double . , . " ", , " ". .

+8
+3

. , .

, IEEE 43.65 + 61.11 - . ( - Python 2.7 Visual ++) , 104.76. .

, , . , , .: -)

+2

, , , 10, , . , , 1/3 10, .3 . , , .

, , . , . , , 10.

10. , , ,

+2

double . < 1 x/y. , . , .

:)

+1

base-10, -10 . ( int "" "" .)

IEEE-754 .1 .01. , , , , - , .

:

#include <stdio.h>

int main(int argc, char* argv[]) {
    float f, g;
    double d, e;
    long double l, m;

    f=0.1;
    g=f*f;
    d=0.1;
    e=d*d;
    l=0.1;
    m=l*l;
    printf("%40.40f, %40.40f, %40.40Lf\n", g, e, m);
    return 0;
}

$ ./fp
0.0100000007078051567077636718750000000000,
0.0100000000000000019428902930940239457414,
0.0100000000000000011102569059430467124372

0.01, , .

.

+1

? 104.76, :

class Program
{
    static void Main(string[] args)
    {
        double d1 = 43.65;
        double d2 = 61.11;
        double d3 = d1 + d2;
        Console.WriteLine(d3);
        Console.ReadLine();
    }
}

104.76000213623

class Program
{
    static void Main(string[] args)
    {
        float d1 = 43.65f;
        float d2 = 61.11f;
        double d3 = d1 + d2;
        Console.WriteLine(d3);
        Console.ReadLine();
    }
}

Make sure you convert from float to double, which could cause this problem.

0
source

All Articles