Advertisement
18126

HW2ex3

Mar 13th, 2022
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.91 KB | None | 0 0
  1. #include <math.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. double calculate(double* a, double* b, double* c, double* x1, double* x2) {
  6.    
  7.     //ax2 + bx = c
  8.     //D = b2 - 4*a*c
  9.     //x1 = -b + sqrt(D) / 2
  10.     //x2 = -b - sqrt(D) / 2
  11.    
  12.     double D;
  13.     D = *b * *b - 4 * *a * *c;
  14.     if(D > 0) {
  15.         *x1 = ((-1) * *b + sqrt(D)) / 2;
  16.         *x2 = ((-1) * *b - sqrt(D)) / 2;
  17.         return 0;
  18.     } else if(D < 0) {
  19.         return 2;
  20.     } else {
  21.         *x1 = ((-1) * *b + sqrt(D)) / 2;
  22.         *x2 = *x1;
  23.         return 0;
  24.     }
  25.    
  26.  
  27. }
  28.  
  29. int main(int args, char *argv[]) {
  30.     double a, b, c;
  31.     double x1, x2;
  32.    
  33.     a = atof(argv[1]);
  34.     b = atof(argv[2]);
  35.     c = atof(argv[3]);
  36.  
  37.     if(calculate(&a, &b, &c, &x1, &x2) == 0) {
  38.         printf("x1: %lf\n", x1);
  39.         printf("x2: %lf\n", x2);
  40.     } else {
  41.         fprintf(stderr, "No real roots\n");
  42.     }
  43.  
  44.     return 0;
  45.  
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement