01: // 2nd order polynomial equation, math predefined functions   pow(), sqrt()
02: #include <stdio.h>
03: #include <stdlib.h>
04: #include <math.h>   // we need this for math functions!
05: 
06: int main() {
07:     double a, b, c;
08:     double root1, root2, realPart, imaginaryPart;
09: 
10:     // Input coefficients
11:     printf("Enter coefficients a, b, and c of an equation like ax^2 + bx + c = 0: ");
12:     scanf("%lf %lf %lf", &a, &b, &c);
13: 
14:     double discriminant = pow(b, 2) - 4 * a * c; // double pow(double base, double exponent);, in this case b*b is definitely more quick and efficient
15: 
16:     if (discriminant > 0) {
17:         // Two real and distinct roots
18:         root1 = (-b + sqrt(discriminant)) / (2 * a); // double sqrt(double x);  
19:         root2 = (-b - sqrt(discriminant)) / (2 * a);
20:         printf("Roots are real and distinct: %lg and %lg\n", root1, root2);
21:     } else if (discriminant == 0) {
22:         // One real and equal root
23:         root1 = -b / (2 * a);
24:         printf("Roots are real and equal: %.2lf\n", root1);
25:     } else {
26:         // Complex conjugate roots
27:         realPart = -b / (2 * a);
28:         imaginaryPart = sqrt(-discriminant) / (2 * a);
29:         printf("Roots are complex: %lg + %lgi and %.lg - %lgi\n", realPart, imaginaryPart, realPart, imaginaryPart);
30:     }
31: 
32:     return 0;
33: }
34: 


Se avete commenti o osservaƶioni su questa pagina
mandate un messaggio di posta elettronica a bertoƶƶi@ce.unipr.it