Mohammad Taghi Ghandili Mohammad Taghi Ghandili - 1 month ago 7
C Question

if and else both is being excuted

I have strange problem with a simple c program.

#include<stdio.h>
#include<math.h>
#include<conio.h>
main() {
int a, b, c, delta;
float x1, x2;
printf("Please Enter a,b,c :");
scanf("%d%d%d",&a,&b,&c);
delta = (b * b) - (4 * (a * c));
if(delta < 0){
printf("No roots!");
}
else{
if (delta >= 0){
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
}
}
printf("r1=%f and r2=%f", x1, x2);
getch();

}


when I enter
2 1 1
, it seems, the program executes both
if
and
else
in line 10 and 13.
The output is
No roots!x1=0.0000 and x2=0.0000

what's wrong?

Answer
No roots!x1=0.0000 and x2=0.0000

If there are no roots you actually have undefined behavior because below

printf("r1=%f and r2=%f", x1, x2);

you are trying to print values of x1 and x2 - which are not initialized.

Why did you assume both if and else were executed?