0

I tried to write a code to find the roots of the equation without the mat.h library The code does not work when delta is bigger than zero, why might it be due?

void find_root(){
double a,b,c;
double delta;
double num=0;
double root_1,root_2;

printf("Please Enter the first coefficient");
scanf("%lf",&a);
printf("Please Enter the second coefficient");
scanf("%lf",&b);
printf("Please Enter the third coefficient");
scanf("%lf",&c);
delta=(b*b)-(4*a*c);

if(delta>=0){
    while(delta!=num*num){
    num=num+0.001;
    }
    root_1=(-b+num)/(2*a);
    root_2=(-b-num)/(2*a);
    printf("Your equation %.1lfx^2 + %.1lfx + %.1lf have real roots {%.1lf,%.1lf}",a,b,c,root_1,root_2);
}

else  {
    printf("Your equation %.1lfx^2 + %.1lfx + %.1lf does not have any real roots",a,b,c);
}
}
  • 2
    Exact comparisons between floating point values almost never work, as there's simply too many rounding errors (which compound). You need to do comparisons using an *epsilon* (i.e. make the comparison fuzzy or a little inexact). – Some programmer dude Feb 23 '20 at 16:55
  • Does this answer your question? [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Purple Ice Feb 23 '20 at 16:56
  • Try changing `while(delta!=num*num){` to `while(delta<(num*num)-epsilon || delta>(num*num)+epsilon){` and add `double epsilon = 0.00001;`. – Bob Jarvis - Слава Україні Feb 23 '20 at 17:00
  • Thanks for the answer, I understood –  Feb 23 '20 at 20:08

0 Answers0