-2
int base = 12;

double number = 12.2112;

double c = number - base;
//// c=0.211199999999999983   

this is c++ code, How could I get the outcome: c= 0.2112,

Johnny
  • 5
  • 2
  • 1
    See this [isocpp FAQ](https://isocpp.org/wiki/faq/newbie#floating-pt-errs) – NathanOliver Sep 22 '15 at 18:06
  • [What Every Programmer Should Know About Floating-Point Arithmetic or Why don’t my numbers add up?](http://floating-point-gui.de/) – Steve Sep 22 '15 at 19:25

1 Answers1

0

0.2112 cannot be exactly represented in Floating Point Notation: https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

If it's extremely important to you that 0.2112 be represented exactly, then the usual solution looks a bit like this:

int base = 120000;
int number = 122112;
int c = number - base;

cout << "Value of c: " << (c / 10000.0) << endl;

Know, however, that what we're doing here is implementing fixed-point numbers. If you need fixed-point numbers in your implementation, it may be worthwhile to research and implement a full fixed-point class that does everything you're trying to accomplish here.

Xirema
  • 19,889
  • 4
  • 32
  • 68