Tuesday, July 14, 2009

C program writing (not C++/C#)?

I've unfortunately no gift of C and haven't a clue how to write this program. With less than two days to write something, I turn to you.





Write a structured program to find the roots, using the Newton-Ralphson Method, of the function ax^2+bx+c=y, where a, b and c are any numbers input by the user along an initial guess value of x and a tolerance (convergence). Print out to screen the result of each iteration. Include in the code a means of bailing out of the while loop if 50 iterations have passed without achieving the requied accuracy - along with an error message to the screen "Sorry, unable to find the root to the required accuracy".

C program writing (not C++/C#)?
#include %26lt;stdio.h%26gt;


#include %26lt;math.h%26gt;


int main( int, char ** ) {


double a, b, c, x, t, x2;


int n;


printf( "Enter a, b, c, a starting x and a tolerance:\n" )


if (scanf( "%f%f%f%f%f", %26amp;a, %26amp;b, %26amp;c, %26amp;x, %26amp;t ) %26lt; 5) {


printf( "Not enough values entered\n" );


return 0;


}


for (n=0; n%26lt;50; ++n)


{


/* You'll have to put the convergence stuff in here


and assign the value to x2. */





/* Stop looping if we are within the tolerance. */


if (fabs( x2 - x ) %26lt; t)


break;





x = x2;


}





if (n %26lt; 50) {


/* print out the results */


} else


printf( "Sorry, unable to find the root to the required accuracy\n" );





return 0;


}

mothers day flowers

No comments:

Post a Comment