I have noticed that doubles in java are not at all like doubles in c++.
In fact, Java will be using precisely the same representation for doubles as C++ does, and the arithmetic will (most likely) be producing exactly the same values internally.
The fundamental problem here is that there is not a precise 1-to-1 mapping between binary floating point number representations and decimal representations. Numbers such as 12.3
cannot be precisely represented as binary floating numbers. It is a mathematical impossibility.
To understand this (AND YOU SHOULD), read "What Every Computer Scientist Should Know About Floating-Point Arithmetic".
The difference you are observing, will be due to differences in the formatting code that turns the double values into digits for output. In the Java case, the code is giving the most accurate decimal representation of the actual double that it can achieve. In the C++ case, it is rounding off the least significant digits ... which gives the number you expect, but not the most accurate decimal representation.
Neither approach is wrong. They are just different. If you want Java to display your numbers rounded to a certain number of digits, you can do this using one of the Java formatter classes.
Another alternative is to do all of your calculator arithmetic in Java using the BigDecimal
class. This will give you precise numbers, modulo the limitations of decimal arithmetic that you learned in high school; e.g. you can't represent fractions like 1/3 precisely in decimal. The downsides are that BigDecimal
arithmetic is many orders of magnitude slower than floating point, and the APIs are more cumbersome to use.