0

I know this may be basic but the problem is that I was experimenting with a small program to implicitly convert data types into the highest order by Java, C++ hierarchy and the results were interesting, for example:

public class idk
{
    public static void main(String args[])
    {
        double a;
        int b = 4565;
        char c = 'z';
        byte d = 1;
        short e = 32;
        long f = 74539;
        float g = 478.68f;
        a = b+c+d+e+f+g;
        System.out.println(a);
    }
}

Here the output came to be

79737.6796875

But it should have been

79737.68

and in C++

#include <iostream>

using namespace std;

int main()
{
    double a;
    int b = 4565;
    char c = 'z';
    short e = 32;
    long f = 74539;
    float g = 478.68f;
    a = b+c+d+e+f+g;
    
    if(a == 79736.6796875)
    cout<<a;

    return 0;
}

And it did print a, so the end is that the decimal numbers are being altered and if the float variable was changed to double, then all the problems vanish, why is that and what is the solution?

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
Ham Lemon
  • 3
  • 2
  • 1
    ***But it should have been*** No this is actually wrong. Some numbers are impossible to represent by the floating point hardware implementation. This calculator should help you understand this behavior and what is stored: [https://www.h-schmidt.net/FloatConverter/IEEE754.html](https://www.h-schmidt.net/FloatConverter/IEEE754.html) – drescherjm Dec 07 '21 at 16:25
  • the calculator gives a very small error whereas my error are in 10^-2 orders, why? – Ham Lemon Dec 07 '21 at 16:50
  • Put `79737.68` into the calculator and see what value it returns. – drescherjm Dec 07 '21 at 16:58

0 Answers0