#include "stdafx.h"
#include <iostream>
usingnamespace std;
void main()
{
double a = 2.09, b=0;
cout << a << endl;
a = a - 2.09;
cout << "a - 2.09 = " << a << endl;
a = 2.09;
a = a - .09;
cout << "a - .09 = " << a << endl;
a = a - 2;
cout << "a - 2 = " << a << endl;
cin >> b;
}
Output:
2.09
a - 2.09 = 0
a - .09 = 2
a - 2 = -2.22045e-016
why 'a' becomes -2.22045e-016
If instead of 2.09 I use 1.09, 3.09 or 4.09 the final output is fine > a - 2 = 0;
#include "stdafx.h"
#include <iostream>
usingnamespace std;
void main()
{
double a = 2.09, b=0;
cout << a << endl;
a = a - 2.09;
cout << "a - 2.09 = " << a << endl;
a = 2.09;
a = a - .09;
cout << "a - .09 = " << a << endl;
a = a - 2.0;
cout << "a - 2.0 = " << a << endl;
cin >> b;
}
2.09
a - 2.09 = 0
a - .09 = 2
a - 2.0 = -2.22045e-016
Come to think of it, I think this may be "working as intended."
I'm pretty sure that floats, doubles, etc have a limited amount of precision, based on your architecture. As you approach 0, you end with an infinitely smaller number, which the compiler attempts to print out to it's best ability, where with a definable number, that kind of imprecision is actually ignored by the compiler in favor of the gross precision values that are determined by the user/program editing.
right at the beginning of main() and run the program again. That would take care of things like 0.000000000000000222045 at least as far as the displayed output is concerned.
Well then you must have something that is not a C++ compiler. It's probably very similar to a C++ compiler. Most of the time, it won't make any difference, I expect. Still, it's important to know when you're writing C++ and when you're not - if you ever have to work with other coders, or you swicth compiler, you'll run into problems if you don't know.