1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>
#define MAX_TERMS 100
typedef struct { int coefficient; int exponent; } Term;
void parsePolynomial(char* input, Term* polynomial, int* numTerms); void derivative(Term* polynomial, int* numTerms); void printPolynomial(Term* polynomial, int numTerms);
int main() { char input[100]; Term polynomial[MAX_TERMS]; int numTerms = 0;
printf("请输入一元多项式:"); fgets(input, sizeof(input), stdin);
parsePolynomial(input, polynomial, &numTerms); if (numTerms == 0) { printf("输入格式有误!\n"); return 1; }
derivative(polynomial, &numTerms);
printf("求导后的多项式为:"); printPolynomial(polynomial, numTerms);
return 0; }
void parsePolynomial(char* input, Term* polynomial, int* numTerms) { char* token = strtok(input, "+-\n");
while (token != NULL) { int coefficient = 0; int exponent = 0;
if (sscanf(token, "%dx^%d", &coefficient, &exponent) == 2) { polynomial[*numTerms].coefficient = coefficient; polynomial[*numTerms].exponent = exponent; (*numTerms)++; } else if (sscanf(token, "%dx", &coefficient) == 1) { polynomial[*numTerms].coefficient = coefficient; polynomial[*numTerms].exponent = 1; (*numTerms)++; } else if (sscanf(token, "%d", &coefficient) == 1) { polynomial[*numTerms].coefficient = coefficient; polynomial[*numTerms].exponent = 0; (*numTerms)++; }
token = strtok(NULL, "+-\n"); } }
void derivative(Term* polynomial, int* numTerms) { for (int i = 0; i < *numTerms; i++) { polynomial[i].coefficient *= polynomial[i].exponent; polynomial[i].exponent--; }
for (int i = 0; i < *numTerms; i++) { if (polynomial[i].exponent < 0) { for (int j = i; j < *numTerms - 1; j++) { polynomial[j] = polynomial[j + 1]; } (*numTerms)--; i--; } }
for (int i = 0; i < *numTerms; i++) { if (i > 0 && polynomial[i].coefficient < 0) { polynomial[i].coefficient = -polynomial[i].coefficient; } } }
void printPolynomial(Term* polynomial, int numTerms) { for (int i = 0; i < numTerms; i++) { if (polynomial[i].coefficient > 0 && i != 0) { printf("+"); } if (polynomial[i].exponent == 0) { printf("%d", polynomial[i].coefficient); } else if (polynomial[i].exponent == 1) { printf("%dx", polynomial[i].coefficient); } else { printf("%dx^%d", polynomial[i].coefficient, polynomial[i].exponent); } } printf("\n"); }
|