-1

I have made a simple addition function, but getting wrong summation values, sorry if it is a naive thing to look for. But really want to know why is this happening. I want an alternative solution for this. Thanks in advance!

I am using notepad++ to write the code, and gcc compiler in the windows command prompt to execute the code.


#include <stdlib.h>
#include <stdio.h>

float addit(float num1, float num2)
    {
        float sumit;
        sumit = num1 + num2;
        return sumit;
    }

int main()
{
    float num1, num2;
    float answer = 0.000000;

    printf("Enter first number: ");
    scanf("%f", &num1);
    printf("Enter second number: ");
    scanf("%f", &num2);

    answer = addit(num1, num2);
    printf("The summation is: %f", answer);

    return 0;
}

The expected output of the addition of 2345.34 and 432.666 is 2778.006. But, after execution it shows 2778.006104.

Windows cmd window showing execution result as 2778.006104

deepds14
  • 41
  • 2
  • 4
    The `float` type typically has 6-7 decimal digits of accuracy. You're pushing beyond those limits and finding that it isn't accurate. See [Is floating-point math broken?](https://stackoverflow.com/questions/588004/) for more details. – Jonathan Leffler Apr 10 '19 at 17:01
  • 1
    Floats and Doubles are not exact numbers in C. There is a rounding error. – Kevin Vandy Apr 10 '19 at 17:01
  • 3
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – SiggiSv Apr 10 '19 at 17:12

1 Answers1

0

Welcome to the wonderful world of floating point values! Consider this: between 0 and 1, there are infinitely many numbers. There's 0.1, and there's 0.01, and there's 0.001, and so on. But computers do not have infinite space, so how are we supposed to store numbers? Our solution was to limit the precision of the numbers we stored. As others have mentioned, java's float data type only has 6 or 7 digits of accuracy (in base 10). Because of this, you cannot necessarily guarantee that the result of a mathematical operation on floats will be 100% accurate. You can only be sure that the first 6-7 digits of the result will be.

EKW
  • 2,059
  • 14
  • 24