Fancy input is certainly a nice feature, though not usually really necessary in most cases. A more simplified format might help get things up and running in the meantime.
Example using command line parameters as input:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_TERMS 100
void reverse_polynomial(double* polynomial, size_t length)
{
double* left = polynomial;
double* right = left + length;
while(left < --right)
{
double swap = *right;
*right = *left;
*left++ = swap;
}
}
double evaluate_polynomial(double base, double* polynomial, size_t length)
{
double sum = 0;
for(size_t power = 0; power < length; ++power)
sum += polynomial[power] * pow(base, power);
return sum;
}
void print_polynomial(double* polynomial, size_t length)
{
size_t degree = length - 1;
for(size_t index = 0; index < length; ++index)
{
size_t power = degree - index;
double value = polynomial[power];
if(value == 0)
continue;
if(power == degree)
printf("%g", value);
else
{
if(value < 0)
printf(" - %g", -value);
else
printf(" + %g", value);
}
if(power == 1)
putchar('x');
else if(power != 0)
printf("x^%zu", power);
}
puts("");
}
#define die(message)\
do\
{\
puts(message);\
printf("Usage: %s [START] [END] [INCREMENT] [TERMS...]\n", argv[0]);\
printf("Example: %s -1 1 0.1 2 0 -12 0.5 -1.5e3\n", argv[0]);\
puts(" (From -1 to 1 in 0.1 increments evaluate 2x^4 - 12x^2 + 0.5x - 1500)"); \
exit(EXIT_FAILURE); \
}\
while(0)
#define usage() die("")
int main(int argc, char** argv)
{
if(argc < 5)
usage();
size_t adx = 1;
double current = atof(argv[adx++]);
double end = atof(argv[adx++]);
if(current > end)
die("END range must be less than START range");
double increment = atof(argv[adx++]);
if(increment == 0)
die("Increment must be nonzero");
double terms[MAX_TERMS];
size_t count = 0;
for(;;)
{
char* text = argv[adx++];
if(text == NULL)
break;
if(count >= MAX_TERMS)
die("Too many terms!");
terms[count++] = atof(text);
}
reverse_polynomial(terms, count);
print_polynomial(terms, count);
puts("*** Evaluate ***");
while(current <= end)
{
double x = current;
printf("x: %g\n", x);
double y = evaluate_polynomial(x, terms, count);
printf("y: %g\n", y);
current += increment;
puts("");
}
return EXIT_SUCCESS;
}