fork(7) download
  1. /* 8. An equation of the form
  2. ax^2 + bx + c = 0
  3. is known as a quadratic equation.The values of a, b, and c in the preceding example
  4. represent constant values. So
  5.  
  6. 4x^2 - 17x - 15 = 0
  7.  
  8. represents a quadratic equation where a = 4, b = –17, and c = –15.The values of x
  9. that satisfy a particular quadratic equation, known as the roots of the equation, can
  10. be calculated by substituting the values of a, b, and c into the following two
  11. formulas:
  12. If the value of b^2–4ac, called the discriminant, is less than zero, the roots of the
  13. equation, x1 and x2, are imaginary numbers.
  14. Write a program to solve a quadratic equation.The program should allow
  15. the user to enter the values for a, b, and c. If the discriminant is less than
  16. zero, a message should be displayed that the roots are imaginary; otherwise,
  17. the program should then proceed to calculate and display the two roots of
  18. the equation. (Note: Be certain to make use of the squareRoot function that
  19. you developed in this chapter.) */
  20.  
  21. #include <math.h>
  22. #include <stdio.h>
  23.  
  24. //function to find absolute value
  25. float absoluteValue (float d)
  26. {
  27.  
  28.  
  29. if ( d < 0 )
  30. d = -d;
  31. return d;
  32. }
  33.  
  34. // Function to compute the square root of a number
  35.  
  36. float squareRoot (float d)
  37. {
  38.  
  39. const float epsilon = .00001;
  40. float guess = 1.0;
  41.  
  42. while ( absoluteValue (guess * guess - d) >= epsilon )
  43. guess = ( d / guess + guess ) / 2.0;
  44.  
  45. return guess;
  46. }
  47.  
  48. // quadratic equation function
  49. void qe (float a, float b, float c)
  50. {
  51. float x1, x2;
  52. float d;
  53.  
  54. d = (pow (b, 2) - (4 * a * c));
  55.  
  56. if (d < 0)
  57. printf ("x1 and x2 are imaginary numbers");
  58.  
  59. x1 = (-b + squareRoot (d)) / (2 * a);
  60.  
  61. printf("x1 is %f", x1);
  62.  
  63. x2 = (-b - squareRoot (d)) / (2 * a);
  64.  
  65. printf("x2 is %f", x2);
  66.  
  67.  
  68. }
  69.  
  70. int main (void)
  71. {
  72. float a, b, c;
  73.  
  74. printf("What is a?: \n");
  75. scanf("%f", &a);
  76.  
  77. printf("What is b?: \n");
  78. scanf("%f", &b);
  79.  
  80. printf("What is c?:\n");
  81. scanf("%f", &c);
  82.  
  83.  
  84. qe (a, b, c);
  85.  
  86. return 0;
  87. }
Success #stdin #stdout 0.01s 1724KB
stdin
-6
13
-6
stdout
What is a?: 
What is b?: 
What is c?:
x1 is 0.666667x2 is 1.500000