tags:

views:

137

answers:

3
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
    int a,b,c;
    float d,d2;
    printf(" Enter a,b and c:");
    scanf("%d %d %d",&a,&b,&c);
    d=b*b-4*a*c;

    if(d<0)
    {
        printf("(%d+i%d)/%d",(-b,sqrt(d),2*a));
        printf("(%d-i%d)/%d",(-b,sqrt(d),2*a));
    }
    else
    {
        printf("(%d+%d)/%d",(-b,sqrt(d),2*a));
        printf("(%d-%d)/%d",(-b,sqrt(d),2*a));
    }

getch();
}
+7  A: 

Several problems here.

You must leave out the parenthesis here:

printf("(%d+i%d)/%d",(-b,sqrt(d),2*a)); /* wrong */
printf("(%d+i%f)/%d",-b,sqrt(d),2*a);   /* right */

With the parentheses, you're passing printf only two arguments: the format string, and an expression using the comma operator. That results in the value of the last expression, 2*a. The behaviour of the remaining two format specifiers is undefined, and this might even lead to a program crash.

The other problem is that you're using %d in your format string, even where the number might not be an integer. Use %f to format float numbers instead.

Replace sqrt by sqrtf to prevent unnecessary conversions between float and double.

Another problem is that sqrt only works on nonnegative numbers. Replace by sqrtf(-d) in the d<0 case.

Thomas
still it says DOMAIN ERROR
fahad
You're taking the square root of a negative number. I added that to my post.
Thomas
Thanks worked.Couldnt find sqrtf() anywhere in help :(
fahad
+1  A: 

Try this Hope you will be done

if(d<0)
    {
        printf("(%d+i%d)/%d",-b,sqrt(d),2*a);
        printf("(%d-i%d)/%d",-b,sqrt(d),2*a);
    }
    else
    {
        printf("(%d+%d)/%d",-b,sqrt(d),2*a);
        printf("(%d-%d)/%d",-b,sqrt(d),2*a);
    }
}

Thanks

Muhit
A: 

int main(void) { int a,b,c; float d,d2; printf(" Enter a,b and c:"); scanf("%d %d %d",&a,&b,&c); d=b*b-4*a*c;

    if(d<0)
    {
        printf("(%d+i%f)/%d",-b,sqrt(d),2*a);
        printf("(%d-i%f)/%d",-b,sqrt(d),2*a);
    }
    else
    {
        printf("(%d+%f)/%d \n",-b,sqrt(d),2*a);
        printf("(%d-%f)/%d \n",-b,sqrt(d),2*a);
    }


}

This works fine for me with inputs a=1,b=2,c=1. You may actually want to find the exact roots by evaluation the expression

(x1,x2) = -b +/- sqrt(b^2-4ac)/2a

Otherwise the output will be as follows :

(-2+0.000000)/2 (-2-0.000000)/2
Praveen S