go to previous page   go to home page   go to next page

Answer:

The program ends because the first character in the buffer is 'q' . This is not quite what the specifications asked for but there is little advantage here in testing for an exact match.


Complete Program


#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <math.h>

int main()
{
  double a, b, c, x1, x2;
  double discriminant;

  char buffer[50] = { 0 }; /* Initialize buffer */

  /* Loop until the user enters q or Q */
  while (buffer[0] != 'q' && buffer[0] != 'Q')
  {
    /* Get coefficients */
    printf("\nEnter a b c: ");
    scanf(" %lf %lf %lf", &a, &b, &c);
    gets(buffer); /* eat the end of line */

    /* If legit quadratic */
    if (a != 0.0)
    {
      discriminant = b*b - 4.0*a*c;

      /* Three cases */
      if (discriminant < 0.0)
      {
        printf("No real roots\n");
      }
      else if (discriminant == 0.0)
      {
        x1 = -b / (2 * a);
        printf("One root: %lf\n", x1);
      }
      else
      {
        x1 = (-b + sqrt(discriminant)) / (2.0*a) ;
        x2 = (-b - sqrt(discriminant)) / (2.0*a) ;
        printf("Two solutions: x = %lf and x = %lf\n", x1, x2);
      }
    }
    else
    {
      printf("Coefficient a must not be zero\n");
    }

    /* prepare for next set of coefficients */
    printf("Hit enter to continue, q enter to quit: ");
    gets(buffer);

  }
  printf("Bye!\n");

}

Above is the complete program. The logic to process the coefficients and write out the roots (or error message) has been added.

You may wish to copy and paste the program into a project and compile and run it. The line

#define _CRT_SECURE_NO_WARNINGS 1

is needed if you are using gets() with Microsoft Visual C++ .


QUESTION 11:

Could the program be modified to find complex roots?