0

For this C++ program...

#include <iostream>

using namespace std;

int main () {
  float d = 0.1;
  float e = 0.2;
  float result = d + e;
  bool is_equal = (result == 0.3);

  cout << result << endl;
  cout << is_equal << endl;

  return 0;
}

The answer printed to the console is...

0.3
0

Questions:

  • Why isn't the value of result equal to 0.30000000000000004, like it is in any other languages I've used (Ruby, JavaScript, Elixir)?
  • If the printed result is 0.3, why isn't result equal to 0.3?
  • What is the actual value of result?
popedotninja
  • 1,170
  • 1
  • 12
  • 23
  • 1
    It depends on how you convert it to a string. – SLaks Nov 02 '17 at 21:38
  • 1
    The value is indeed likely `0.30000000000000004` its just that the default precision of `std::cout` for `float` is not printing that many decimals. You can see how to modify that [here](https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) – Cory Kramer Nov 02 '17 at 21:39
  • 1
    `<<` for floating point does some polite formatting for you. [Use `std::setprecision` to make it show more digits.](http://en.cppreference.com/w/cpp/io/manip/setprecision) – user4581301 Nov 02 '17 at 21:40
  • 1
    You can always inspect `result` value in debugger. Also using `==` to compare floating point number with literal (or two floating point numbers) is not a good idea. – user7860670 Nov 02 '17 at 21:41
  • Also handy: [`std::boolalpha` for when you want nice true/ false output instead of 1/0.](http://en.cppreference.com/w/cpp/io/manip/boolalpha) – user4581301 Nov 02 '17 at 21:43
  • Referencing the question that my question is (apparently) a duplicate of, here's an example of printing w/ precision -- https://gist.github.com/amorphid/37e935f679afcf6addeebbdd13822276 – popedotninja Nov 02 '17 at 21:57
  • The first duplicate question was a poor choice. The reason why your comparison fails is because floating point math is fundamentally broken. See the second duplicate question. In fact, the second question also uses the fact that 0.1 + 0.2 is not 0.3, as an example. – Sam Varshavchik Nov 02 '17 at 22:23
  • removed "Handling doubles with large integer parts" from the dupe list: `0` is not a large integer part, and that question has little to do with this one – M.M Nov 02 '17 at 22:38

0 Answers0