Aug 15, 2020 at 10:26am UTC
I'm trying to write a program that does the following :
1- input "x" and "y"
2- "i" goes up by i=+0.004
3- When "y == i" , I want the program to execute "w".
4- When I put "X=0.2" , "Y=0.04" ... "i" and "y" meat in "0.04" but doesn't execute "w" ? .. the statement "IF" doesn't work ?
Where is the problem?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
using namespace std;
int main() {
double x,y,w;
cout<<"X = " ;
cin >> x;
cout<<"Y = " ;
cin >> y;
for ( double i=0 ; i<0.4 ; i=i+0.004 ){
if (y==i) {
w=x+( i * 2.5 );
cout<<"w = " << w << endl;
} else {
cout<<"i = " << i << endl;
cout<<"y = " << y << endl;
}
}
return 0;
}
And thank you in advance
Last edited on Aug 15, 2020 at 10:48am UTC
Aug 15, 2020 at 11:33am UTC
Here, run this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
std::cout << std::fixed;
std::cout << std::setprecision(20);
double x,y,w;
cout<<"X = " ;
cin >> x;
cout<<"Y = " ;
cin >> y;
for ( double i=0 ; i<0.4 ; i=i+0.004 )
{
if (y==i) {
w=x+( i * 2.5 );
cout<<"w = " << w << endl;
} else {
cout<<"i = " << i << endl;
cout<<"y = " << y << endl;
}
}
return 0;
}
Now you'll see that y and i are never the same value.
Here you can enter some numbers and see what the floating point numbers really represent:
https://www.h-schmidt.net/FloatConverter/IEEE754.html
Last edited on Aug 15, 2020 at 11:40am UTC