weird problem in while loop

when ever i run the program its send me to a infinit loop
where its suppose to stop after 200 loops
i already check that by doing a for loop when (int I = 0;I<200;I++)
and i caculate it in my notebook
why its keep sendign me to infnit loop?!?!?!??!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>

using namespace std;

int main() {

	double A = 50;
	double B = 70;
	double pyA , pyB;
	double cao = 0;

	pyA = (A * 0.03);
	pyB = (B * 0.02);

	while(A != B) {
		A = A + pyA;
		B = B + pyB;
		cout << A << endl;
		cout << B << endl;
	}

	return 0;
}
doubles are approximations. If A and B aren't EXACTLY equal, your loop will never terminate.
so what i need to do to fix this? i mean which type i need to use?
and if i do:
1
2
3
4
5
6
for(int I = 0;I<200;I++) {
       pyA = (A * 0.03);
	pyB = (B * 0.02);
cout << A << endl;
cout << B << endl;
}


they both equals to 350....
B is actually rounded to 350. Technically, by this code, it's 349.99999999999920 after 200. A is 350.0000000000. So they're technically not equal.
so what i got to do?
Change

while ( A != B )

to something like

1
2
3
4
5
const double d = .00001; // or however arbitrarily small you need the difference to be.

then: 

while ( fabs( A-B ) > d)


This will end your loop whenever the difference between A and B is arbitrarily small.
Topic archived. No new replies allowed.