Synthedic Division

Need to find the problem with this code...it infinitely loops.
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// This program checks for factors of polynomial equation by using synthedic division.// 
#include <iostream.h>
int main ()
{
	double a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, s;
	double one, two, three, four, five;
	cout << "x5= "; cin >> a;
	cout << "x4= "; cin >> b;
	cout << "x3= "; cin >> c;
	cout << "x2= "; cin >> d;
	cout << "x= "; cin >> e;
	cout << "1= "; cin >> f;
    k=-25;
	s=0;
	while (k<25)
	{
		cout << k << endl;
		
		k++;
		h=k*a;
		i=b+h;
		j=k*i;
		g=c+j;
		l=k*g;
		m=d+l;
		n=k*m;
		o=e+n;
		p=k*o;
		q=f+o;
// when q=0 the variable k is working factor of the polynomial//
		if (q=0)
		{
			s++;
			if (s=1)
				one=k;
			if (s=2)
				two=k;
			if (s=3)
				three=k;
			if (s=4)
				four=k;
			if (s=5)
				five=k;
		}
	}

	cout<< "factors: " << one << ", " << two << ", " << three << ", " << four << ", " << five ;
	
	return 0;
}
				
If you initialize you variables(one, two, three, four, five) with say 0;
1
2
3
4
5
one = two = three = four = five = 0.0;
//or
one = 0.0;
//...
five = 0.0;

You will notice the you never enter the if(q=0) and you probably meant
1
2
3
4
if(q == 0)
{
//do stuff
}


a good habit is to always initialize your variables.

the loop works under VC2008(Microsoft's compiler) professional and Devc++ (gcc\g++ compiler) on Windows XP pro sp2.

what compiler and operationing system are you using?
try casting the sentinel variable to int when incrementing and checking for loops:
1
2
3
4
5
6
while((int)k < 25)
{
//do stuff
(int)k++; //or instead of ++ operator: k+=1.0;
//do stuff
}


some systems might be incrementing the float part of your variable:
1
2
3
4
5
6
while(k < 25)
{
//do stuff
k++;//here k in your system is probably -24.99 and then -24.98 and so on hence the the feeling of a infinite loop
//do stuff
}

it happened to me once :(
if you have a good debugger\IDE you can watch the variables while the loop increments.
more info:
http://www.cplusplus.com/doc/tutorial/variables.html
http://www.cplusplus.com/doc/tutorial/operators.html
Jeff
Last edited on
Topic archived. No new replies allowed.