Mohammad Taghi Ghandili Mohammad Taghi Ghandili - 1 year ago 62
C Question

if and else both is being excuted

I have strange problem with a simple c program.

main() {
int a, b, c, delta;
float x1, x2;
printf("Please Enter a,b,c :");
delta = (b * b) - (4 * (a * c));
if(delta < 0){
printf("No roots!");
if (delta >= 0){
x1 = (-b + sqrt(delta)) / (2 * a);
x2 = (-b - sqrt(delta)) / (2 * a);
printf("r1=%f and r2=%f", x1, x2);


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

what's wrong?

Answer Source
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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download