This question already has an answer here:
- C++ floating point accuracy in while loops 4 answers
- Is floating point math broken? 27 answers
I am trying to get this code to work, so I basically want to add 0.01 to x and display it accordingly with every loop, but somehow it never shows x = 2, so the "if ( x == 2 )" is not being executed. Also, when using the condition "x < 3" it actually adds up to 3, while "x < 2" only adds up to 1.99.
thank you
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
for (double x = 1.0; x <= 2;x+=0.01)
{
if ( x == 2 )
cout << " x(" << setfill('0') << fixed << left << setw(14) << setprecision(14) << x << ") = 2" << "\n";
else if (x < 2)
cout << " x(" << setfill('0') << left << setw(14) << setprecision(14) << x << ") < 2" << "\n";
else
cout << " x(" << setfill('0') << left << setw(14) << setprecision(14) << x << ") > 2" << "\n";
}
return EXIT_SUCCESS;
}
Aucun commentaire:
Enregistrer un commentaire