Advertisement
malinaX

fizyka.c

Oct 13th, 2020
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.24 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. void findDerivative(char **dst, char *src, int deg) {
  6.     int a = strtol(src, &src, 10);
  7.     if (a != 0) {
  8.         a *= deg;
  9.     } else if (strlen(src) > 0) {
  10.         a = deg;
  11.     }
  12.     *dst = malloc(1024);
  13.     itoa(a, *dst, 10);
  14.     if (strlen(src) > 0) {
  15.         strcat(*dst, "*");
  16.         strcat(*dst, src);
  17.     }
  18.     strcat(*dst, "*t^");
  19.     char *c = malloc((deg - 1) / 10 + 2);
  20.     itoa(deg - 1, c, 10);
  21.     strcat(*dst, c);
  22.     dst = realloc(*dst, strlen(*dst) + 1);
  23. }
  24.  
  25. int main(void) {
  26.     printf("podaj wspolczynniki rownania w kolejnosci od tego przy najnizszej "
  27.            "potedze (czyli wyrazu wolnego) oddzielone spacja (jezeli ktorys "
  28.            "jest rowny 0 to trzeba to 0 napisac): ");
  29.     char *buf = malloc(1024);
  30.     if (buf == NULL) {
  31.         printf("Memory allocation error\n");
  32.         exit(1);
  33.     }
  34.     fgets(buf, 1024, stdin);
  35.     while (*buf == ' ')
  36.         buf++;
  37.     char **formula;
  38.     char *ptr = buf;
  39.     size_t degree = 0;
  40.     while (*ptr != '\n') {
  41.         while (*ptr != ' ' && *ptr != '\n')
  42.             ptr++;
  43.         degree++;
  44.         while (*ptr == ' ')
  45.             ptr++;
  46.     }
  47.     //printf("%d\n", degree);
  48.     formula = malloc(degree * sizeof(char *));
  49.     degree--;
  50.     if (formula == NULL) {
  51.         printf("Memory allocation error\n");
  52.         exit(1);
  53.     }
  54.     ptr = buf;
  55.     char *strBegin = buf;
  56.     size_t length, i = 0;
  57.     while (*ptr != '\n') {
  58.         while (*ptr != ' ' && *ptr != '\n')
  59.             ptr++;
  60.         length = ptr - strBegin;
  61.         //printf("***%d***\n", length);
  62.         formula[i] = malloc(length + 1);
  63.         strncpy(formula[i], strBegin, length);
  64.         formula[i][length] = '\0';
  65.         i++;
  66.         while (*ptr == ' ')
  67.             ptr++;
  68.         strBegin = ptr;
  69.     }
  70.     free(buf);
  71.  
  72.     char **derivative = malloc(degree * sizeof(char *));
  73.     for (size_t i = 1; i <= degree; i++) {
  74.         findDerivative(derivative + i - 1, formula[i], i);
  75.     }
  76.  
  77.     printf("v(t) = ");
  78.     for (size_t i = 0; i < degree; i++) {
  79.         printf("%s ", derivative[i]);
  80.         if (i != degree - 1)
  81.             printf("+ ");
  82.         else
  83.             printf("\n");
  84.     }
  85.     return 0;
  86. }
  87.  
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement