In: Computer Science
My current code that is not working correctly
#include<stdio.h>
#include<math.h>
int main() {
//variable declaration
int a,b,c,D,n;
double x1,x2;
double realPart, imagPart;
do {
// this set of code blocks prompts a message to the user and then
read the integer entered and stores it as an integer
printf("Enter a value for a:\n");
scanf("%d",&a);
printf("Enter a value for b:\n");
scanf("%d",&b);
printf("Enter a value for c:\n");
scanf("%d",&c);
printf("You entered the Equation \n");
printf("%dx^2%+dx%+d=0\n",a,b,c);
D = b*b - 4*a*c;
if (D<0)
{
printf("Equation has two complex roots.\n");
realPart = -b/(double)(2*a);
imagPart = sqrt(-D)/(2*a);
printf("X= %.1lf%lfi or X= %.1lf%lfi\n", realPart, + imagPart,
realPart, imagPart);
}
else { //real roots
x1 = (-b + sqrt(D))/(2*a);
x2 = (-b - sqrt(D))/(2*a);
if(x1==x2){
printf("Equation has two identical real roots.\n");
printf("x = %.2lf\n",x1);
}
else{
printf("X= %.1lf or X= %.2lf\n", x1, x2);
printf("Equation has two distinct real roots.\n");
}
}
printf("Another Equation? (Enter 0 to exit)...");
scanf("%d",&n);
}
while(n!=0);
}
WHAT THE CODE NEEDS TO DO IN C LANGUAGE ONLY
Write a program that determines whether a quadratic equation has one real root, two real roots, or imaginary roots. Then, if the roots are real, display the roots of the quadratic equation.
A quadratic equation is of the form ax^2+bx+c=0.
The discriminant of the equation is D=b^2-4ac. If D>0, then there are two distinct real roots. If D=0, then there are two identical real roots, and if D<0, then there are two imaginary roots.
The roots of the equation are found using the quadratic equation:
Procedure
Corrected code :
#include<stdio.h>
#include<math.h>
int main() {
//variable declaration
int a,b,c,D,n;
double x1,x2;
double realPart, imagPart;
do {
// this set of code blocks prompts a message to the user and then read the integer entered and stores it as an integer
printf("Enter a value for a:\n");
scanf("%d",&a);
printf("Enter a value for b:\n");
scanf("%d",&b);
printf("Enter a value for c:\n");
scanf("%d",&c);
printf("You entered the Equation \n");
printf("%dx^2%+dx%+d=0\n",a,b,c);
D = b*b - 4*a*c;
if (D<0)
{
printf("Equation has two complex roots.\n");
realPart = -b/(double)(2*a);
imagPart = sqrt(-D)/(2*a);
printf("X= %.1lf+%lfi or X= %.1lf-%lfi\n", realPart, imagPart, realPart, imagPart);
}
else{ //real roots
x1 = (-b + sqrt(D))/(2*a);
x2 = (-b - sqrt(D))/(2*a);
if (D==0){ //identical real roots
printf("Equation has two identical real roots.\n");
printf("x = %.2lf\n",x1);
}
else{ // 2 distict real roots
printf("X= %.1lf or X= %.2lf\n", x1, x2);
printf("Equation has two distinct real roots.\n");
}
}
printf("Another Equation? (Enter 0 to exit)...");
scanf("%d",&n);
}
while(n!=0);
}
I have made the required corrections to your code and it is now working correctly.
Output :
Complex roots:
Identical real roots:
Identical distinct roots:
Screenshot of the code is attached so that you can understand the intendations.