Advertisement
_takumi

sk1

Nov 27th, 2022 (edited)
2,094
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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 (argc == 1) {
  24.         printf("Please enter one of the following keys: -f, -c\n");
  25.         return 0;
  26.     }
  27.     if (strcmp(argv[1], "-c") == 0) {
  28.         scanf("%lf %lf", &a, &b);
  29.         clock_t begin = clock();
  30.         res = solve(a, b, eps);
  31.         clock_t end = clock();
  32.         printf("%lf\n", res);
  33.         double time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
  34.         printf("Program execution time: %lf\n", time_spent);
  35.     } else if (strcmp(argv[1], "-f") == 0) {
  36.         if (argc != 4) {
  37.             printf("Incorrect input\n");
  38.             return 0;
  39.         }
  40.         FILE *input, *output;
  41.         input = fopen(argv[2], "r");
  42.         output = fopen(argv[3], "w");
  43.         if ((input == NULL) || (output == NULL)) {
  44.             printf("Incorrect input\n");
  45.             return 0;
  46.         }
  47.         fscanf(input, "%lf %lf", &a, &b);
  48.         clock_t begin = clock();
  49.         res = solve(a, b, eps);
  50.         clock_t end = clock();
  51.         fprintf(output, "%lf\n", res);
  52.         double time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
  53.         printf("Program execution time: %lf\n", time_spent);
  54.         fclose(input);
  55.         fclose(output);
  56.     } else {
  57.         printf("Please enter one of the following keys: -f, -c\n");
  58.     }
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement