Tuesday, August 13, 2013

Valuable Lesson Learned

So, last night I was working some more on my programming projects. I got through one of them with no trouble at all, but the next one was giving me a fit. I had to write a program to ask for a value for x, then compute that value in a fifth degree polynomial.

My lesson came after I had corrected the errors and warnings that was keeping the program from compiling. I entered the value I chose for x, and the answer was -6. I entered another value for x... and the answer was still -6. It seemed way off to me.

Here's a look at the code I had written:

#include <stdio.h>

int main (void)
{
   float x, final_value;

   final_value = ((((3*x+2)*x-5)*x-1)*x+7)*x-6;  

       /* By the way, this is an example of Horner's Method, which allows
      for polynomials to be solved, despite C not having an exponential 
      function */

   printf("For the polynomial 3x^5 + 2x^4 - 5x^3 - x^2 + 7x - 6\n");
   printf("Please enter a value for x: ");
   scanf("%f", &x);
   
   printf("Final answer: %.1f\n", final_value);

   return 0;

}

Most people will probably find the issue immediately, but it was totally baffling me. It got to the point where I had to ask my fiance for help. He did some tests, such as changing the final integer of the polynomial to 4. When he ran that test, the answer the program gave was -4 instead of -6!! Fortunately, he knew what to do...

#include <stdio.h>

int main (void)
{
   float x, final_value;

   printf("For the polynomial 3x^5 + 2x^4 - 5x^3 - x^2 + 7x - 6\n");
   printf("Please enter a value for x: ");
   scanf("%f", &x);

   final_value = ((((3*x+2)*x-5)*x-1)*x+7)*x-6;

   printf("Final answer: %.1f\n", final_value);

   return 0;
}

Can we say DERP??? In the first example, x hadn't been initialized because the polynomial came first in the program. It assumed x must be 0, solved the polynomial, stored the final integer (because everything else had been multiplied by 0, because x was equal to 0) as the value of final_value, and returned that every time. It was working correctly! Just not the way I wanted it to!!

In the second example, x is initialized by scanf right off the bat. THEN the program enters it into the polynomial, returning final_value with x equivalent to the value initialized with scanf.

Ahhhhhhhhhhhhh....

No comments:

Post a Comment