Roots of a Polinomyal Function

So, i`ve been strugling with this program, and got it to work using this idea, but i think it takes too much from the pc and wondered if there was an faster way. Also, anybody has any idea on how to find the imaginary roots?
Also, sorry for the bad English :)

The program might be a bit messy, if so, tell me and i`ll try to explain what i thought or rewrite it. Thanks!

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
53
54
55
  #include<stdio.h>
#include<math.h>

#define n 20

double func(int a[n], double x)
{
	double f = a[n - 1];
	for (int i = 0; i < n-1; i++){
		f += a[i] * pow(x, (n - 1 - i)*1.0);
	}
	return f;
}

double rounding(int a[n], double x)
{
	double tmp;
	double j = x, k = x + 0.5;
	for (int i = 0; i < 100; i++)
	{
		tmp = (j + k) / 2;
		if (func(a, j)*func(a, tmp) < 0) k = tmp;
		else j = tmp;
	}
	return tmp;
}

int main()
{
	int a[n] = { 0 }, b = 0, c;
	printf("a1*x^n+a2*x^(n-1)+...+a(n+1)  input n\n");
	scanf_s("%d", &c);

	printf("a1,a2...a(n+1)  input coeficients\n");
	for (int i = 0; i < n-1 - c; i++){
		a[i] = 0;
	}
	for (int i = n-1-c; i < n; i++){
		printf("a%d = ", i - n+2 + c); 
		scanf_s("%d", &a[i]);
	}
	
	puts("\n");
	for (double i = -1000; i < 1000; i +=0.5){
		if (func(a, i) == 0){
			b++;
			printf("x%d = %lf\n", b, i);
		}
		if (func(a, i)*func(a, i + 0.5) < 0){
			b++;
			printf("x%d = %lf\n", b, rounding(a, i));
		}
	}
	return 0;
}
Topic archived. No new replies allowed.