Advertisement
_takumi

sk

Nov 27th, 2022 (edited)
901
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | None | 0 0
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4.  
  5. double f(double x) {
  6.     return x * x * x * x + 2 * x * x * x - x - 1;
  7. }
  8.  
  9. double solve(double a, double b, double e) {
  10.     double c;
  11.     while (b - a > e) {
  12.         c = (a + b) / 2;
  13.         if (f(b) * f(c) < 0)
  14.             a = c;
  15.         else
  16.             b = c;
  17.     }
  18.     return (a + b) / 2;
  19. }
  20.  
  21. int main(int argc, char *argv[]) {
  22.     double res, a, b, eps = 0.000001;
  23.     if (strcmp(argv[1], "-c") == 0) {
  24.         scanf("%lf %lf", &a, &b);
  25.         clock_t begin = clock();
  26.         res = solve(a, b, eps);
  27.         clock_t end = clock();
  28.         printf("%lf\n", res);
  29.         double time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
  30.         printf("Program execution time: %lf\n", time_spent);
  31.     } else if (strcmp(argv[1], "-f") == 0) {
  32.         FILE *input, *output;
  33.         input = fopen(argv[2], "r");
  34.         output = fopen(argv[3], "w");
  35.         fscanf(input, "%lf %lf", &a, &b);
  36.         clock_t begin = clock();
  37.         res = solve(a, b, eps);
  38.         clock_t end = clock();
  39.         fprintf(output, "%lf\n", res);
  40.         double time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
  41.         printf("Program execution time: %lf\n", time_spent);
  42.         fclose(input);
  43.         fclose(output);
  44.     } else {
  45.         printf("Please enter one of the following keys: -f, -c\n");
  46.     }
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement