I know that someone else has asked this question before but they didn't write the program the way I do or make the mistake I made. So here we go.
When I run the program, no matter what, it also prints out the imaginary roots.
#include <stdio.h>
#include <math.h>
#include <windows.h>
typedef struct tagComplex
{
double real;
double imag;
}Complex;
void main(void)
{
SetConsoleTitle("Solve ax^2+bx+c=0");
double a, b, c, delta;
Complex x1, x2;
char k = 'y';
while(k == 'y')
{
printf("Enter the values of a, b, c: ");
scanf("%lf%lf%lf", &a, &b, &c);
while(getchar()!= '\n');
delta = b*b - 4*a*c;
if(delta > 0) //←-------- or delta > 1e-6 ?
{
x1.real = (-b + sqrt(delta))/(2*a);
x2.real = (-b - sqrt(delta))/(2*a);
printf("x1=%.3lf x2=%.3lf\n\n", x1.real, x2.real);
}
if(delta == 0) //←-------- or delta <= 1e-6 ?
{
printf("x1=x2=%.3lf\n\n", -b/(2*a));
}
else
{
x1.real = -b/(2*a);
x1.imag = sqrt(-delta)/(2*a);
x2.real = -b/(2*a);
x2.imag = -sqrt(-delta)/(2*a);
printf("x1=%.3lf+%.3lf i x2=%.3lf+%.3lf i\n\n", x1.real, x1.imag, x2.real, x2.imag);
}
printf("Try another equation? (y or n)\n");
scanf("%c", &k);
}
}
How can I fix it?
Sample data: 1 -4 3
output:
x1=3.000 x2=1.000
x1=2.000+-1.#IO i x2=2.000+1.#QO i
Try another equation? (y or n)