Write a program that calculates the real solutions of a second degree equation \(ax^2+bx+c=0\) by discussing the formula: \(x_{1,2}=\frac{-b\pm\sqrt{b^2-4ac}}{2a}\)
Use a help variable D for the discriminant value \(b^2-4ac\) and decide using D if the equation has one, two or no real solution. Use variables of type int for A, B and C.
Consider also the cases where the user enters null values for A; for A and B; for A, B, and C. View the results and the necessary messages on the screen.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#include <math.h>
void main()
{
int A, B, C;
double D; /* Discriminant */
printf("Real solution of a second degree equation \n");
printf("of the form ax^2 + bx + c = 0 \n\n");
printf("Enter values for a, b, and c : ");
scanf("%i %i %i", &A, &B, &C);
/* Calculus of the discriminant b^2-4ac */
D = pow(B,2) - 4.0*A*C;
if (A==0 && B==0 && C==0) /* 0x = 0 */
printf("Any real is a solution to this equation.\n");
else if (A==0 && B==0) /* Contradiction: c # 0 and c = 0 */
printf("This equation does not have any solutions.\n");
else if (A==0) /* bx + c = 0 */
{
printf("The solution of this first degree equation :\n");
printf(" x = %.4f\n", (double)C/B);
}
else if (D<0) /* b^2-4ac < 0 */
printf("This equation does not have any real solutions.\n");
else if (D==0) /* b^2-4ac = 0 */
{
printf("This equation have a unique real solution :\n");
printf(" x = %.4f\n", (double)-B/(2*A));
}
else /* b^2-4ac > 0 */
{
printf("Real solutions of this equation are :\n");
printf(" x1 = %.4f\n", (-B+sqrt(D))/(2*A));
printf(" x2 = %.4f\n", (-B-sqrt(D))/(2*A));
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Check if a number is palindromic a number using recursion