PROBLEM:
Consider the calculation of the roots of the quadratic equation ax²+bx+c=0, assuming that a is non-zero:-
Write a function in C which will take a, b and c as arguments and resturns the roots as function arguments root1 and root2 (as appropriate). the number of roots will be returned through the type specifier.
Write a main program which prompts the user to enter the values of a, b and c. Then after using a call to the function written above, the program will display the number of roots and their values as appropriate.
SOLUTION:
The function has to be sent the arguments a, b and c, it also requiires two arguments for the roots. These values will be altered by the program so must be pointers. The function returns an integer number for the number of roots. The function declaration will therefore be:-
int root (float a, float b, flot c, float *root1, float *root2);
The rest of the function can now be written.
int root (float a, float b, float c, float *root1, float *root2) { float tmp; tmp = b*b - 4*a*c; if (tmp > 0) { *root1 = (-b + sqrt(tmp))/(2*a); *root2 = (-b - sqrt(tmp))/(2*a); return 2; } else if (tmp == 0) { *root1 = -b/(2*a); return 1; } else return 0; }The main program can now be written. Remember to include the function declaration and math.h as the sqrt function was used.
#include <stdio.h> #include <math.h> int root (float a, float b, float c, float *root1, float *root2); main() { float a,b,c,root1,root2; int num_roots; printf("Enter values for a, b and c\n"); scanf("%f %f %f", &a, &b, &c); num_roots = root(a,b,c,&root1, &root2); if (num_roots == 2) printf("There are 2 real roots with values %f and %f\n", root1, root2); else if (num_roots == 1) printf("There is 1 real root with value %f \n", root1); else printf("There are no real roots\n"); }
Back to Main Page for Lecture 7 |