Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -2x^2+2x-3
- -2x+sinx-3
- -x+sin2x-tanx
- Open the file.
- While there's lines to read:
- Read a line -
- Seperate it by the operands (+,-,/,*)
- For each part:
- Find the power of x,
- Reduce it by one,
- ...(derivating rules) // no way around, you have to implement each function if you want this to work as others mentioned in the comments.
- Reconnect the parts into a string,
- Add it to a list.
- Print each element of the list.
- -2x^2+2x-3 => 2x^2 2x 3
- -2x+sinx-3 => 2x sinx 3
- -x+sin2x-tanx => x sin2x tanx
- -2x^2 + 5x + 4sin3x - 3
- 0 - 2x^2 + 5x + 4sin3x - 3
- 0 [0x^1] (derives as) 0, remove it.
- 2x^2 [2x^2] (derives as) (2*2)x^(2-1) => 4x^1 => 4x
- 5x [5x^1] (derives as) (5x1)x^(1-1) => 5x^0 => 5
- 4sin3x [4sin3x] (derives as) 12cos3x
- 3 [3x^0] (derives as) 0, remove it and preceding '-'
- #define maxlen 50
- #define idx 0 //X variable
- #define idnumber 1 //number
- #define idplus 2 //+ sign
- #define idminus 3 //- sign
- struct foo
- {
- int type[10];//each type can be a number (idnum), +, -, etc.
- int num[10];//if type[i] is number then num[i] identifies that number
- int count;//total number of parts
- };
- void parse_one_line(struct foo *v, const char *s)
- {
- char buf[maxlen];
- memset(buf, 0, maxlen);
- int j = 0;
- //remove white spaces
- for (int i = 0, len = strlen(s); i < len; i++)
- {
- if (s[i] == ' ') continue;
- buf[j] = s[i];
- j++;
- }
- char part[maxlen];
- v->count = 0;
- for (int i = 0, len = strlen(buf); i < len; i++)
- {
- char c = buf[i];
- if (c == 'x')
- {
- v->type[v->count] = idx;
- v->count++;
- }
- else if (c == '+')
- {
- v->type[v->count] = idplus;
- v->count++;
- }
- else if (c == '-')
- {
- v->type[v->count] = idminus;
- v->count++;
- }
- else if (c >= '0' && c <= '9')
- {
- int j = 0;
- memset(part, 0, maxlen);
- for (; i < len; i++)
- {
- c = buf[i];
- if (c >= '0' && c <= '9')
- {
- part[j] = c;
- j++;
- }
- else
- {
- break;
- }
- }
- i--;
- v->num[v->count] = atoi(part);
- v->type[v->count] = idnumber;
- v->count++;
- }
- }
- for (int i = 0; i < v->count; i++)
- {
- switch (v->type[i])
- {
- case idnumber: printf("%d", v->num[i]); break;
- case idx: printf("X"); break;
- case idplus: printf("+"); break;
- case idminus: printf("-"); break;
- default:break;
- }
- }
- printf("n");
- }
- int main()
- {
- struct foo st;
- parse_one_line(&st, "-23x + 2 + 2x - 3");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement