Question

My friend asked to find error in this i am getting the real part of complex solution as zero. can anyone tell me why and how to solve it, thanks for your help

#include<stdio.h>
#include<math.h>
main()
{
    int i,a,b,c,d;
    float x,y;
    printf("ener the values for a,b,c");
    scanf("%d%d%d",&a,&b,&c);
    if(a==0)
    {
        printf("not a quadratc equation");
    }
    else
    {
        d=(b*b-4*a*c);
        if(d==0)
        {
            printf("roots are equal");
            x=-b/(2*a);
            printf("\n%f\n%f",x,x);
        }
        else if(d>0)
        {
            x=(-b+sqrt(d))/(2*a);
            y=(-b-sqrt(d))/(2*a);
            printf("the roots are %f and %f",x,y);
        }
        else if(d<0)
        {
            x=-(b/(2*a));
            printf("%f",x);
            y=(sqrt(-d))/(2*a);
            printf("the roots are %f+i%f and %f-i%f",x,y,x,y);
        }
    }
}
Was it helpful?

Solution

You are performing lots of math on int variables, and storing the result in float. That does not mean that the arithmetic is performed using floating point, it will all be integer.

The sqrt() function returns double, so that saves the imaginary part. For the real part, all the math is integer, so -(b / (2 * a)) will be evaluated using integers and then the final result will be stored in x as a float, of course without ever having any fractional part.

OTHER TIPS

the problem is quite simple just change the code as below

else if(d<0)
    {
      x=(-((float)b/(2*(float)a)));    // type conversion to float from int
      printf("%f",x);
      y=(sqrt(-d))/(2*a);
      printf("the roots are %f+i%f and %f-i%f",x,y,x,y);
    }

The reason was, in quadratic equations complex root calculations if real part is less than 1 (for eg 0.2) it is stored into variable x as integer (integer means only number w/o decimal part) , so you have to do type conversion to get the right data

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top