Why "IF statement " doesn't catch the "=="?

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
0.04 cannot be represented in a floating point number.

You tried to set i to 0.04 ; it is NOT set to 0.04

https://floating-point-gui.de/

NEVER try to exactly compare floating point numbers.
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
I Didnt know that
0.1 + 0.2 != 0.3 ...

I solved the problem like this :

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
#include <iostream>
#include <cmath>
using namespace std;

int main() {
	
	double x,y,w;
	cout<<"X = " ;
	cin >> x;
	cout<<"Y = " ;
	cin >> y;
	
	}
	
	for (double i=0;i < nw ;i=i+0.004){
		//cout<<i<< "  " <<y<<endl;
		if (fabs(y-i) <= 0.01f * fabs(y))  {
			w=x+(i*2.5);
			cout<<"w = "<< w << endl;
		} else {
			//cout<<"No = " << endl;
		}
	}
	
	return 0;
}
Topic archived. No new replies allowed.