Himanshu Kurzekar
Himanshu Kurzekar

Reputation: 11

Whats wrong with my code for finding the roots of the quadratic equation?

If the quadratic equation is written as

ax^2 + bx + c=0

And my code is written as this....

I used temp to get the value of the equation under the square roots.

root1 = [-b + [(b^2 - (4*a*c)]^(1/2) ] / 2*a

root2 = [-b - [(b^2 - (4*a*c)]^(1/2) ] / 2*a

//Program for finding the roots of Quadratic equations
#include<stdio.h>
#include<math.h>

main()
{
    float a,b,c,temp,root1,root2  ;    //aloting the values

    printf(“Finding the roots of variable \n Enter the values of a,b,c ”)  ;
    scanf(“%f,%f,%f”,&a,&b,&c ) ;      //Getting the values of a,b and c

    temp=b*b –(4*a*c) ;                //used in the equation

    if (a!=0 && temp>=0)               //using the condition
    {
        root1 = (-b + sqrt(temp))/a*2 ;
        root2 = (-b - sqrt(temp))/a*2 ;

        printf(“Roots of the equation are %f and %f”, &root1,&root2) ;
    }
    else 
        printf(“There is no real value  of  roots of the given equation ”) ;
}

Upvotes: 0

Views: 146

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

Add (..), should be

    root1 = (-b + sqrt(temp)) / (a * 2);

    root2 = (-b - sqrt(temp)) / (a * 2);

Technically, if a == 0 real (not complex) roots are quite possible, e.g. 0 * x**2 + 3 * x = 6. So

 if (a != 0) {
   if (temp >= 0) {
     ...
   }
   else /* quadratic equation with complex roots only */
     printf(“There is no real value of roots of the given equation”);
 }
 else if (b != 0) {  /* 0 * x**2 + b * x + c = 0 */
   /* the only root */
   float root = -c / b;

   printf(“Root of the equation is %f”, &root);
 }
 else if (c != 0) /* 0 * x**2 + 0 * x + c = 0 */
   printf(“No roots”);
 else             /* 0 * x**2 + 0 * x + 0 = 0 */
   printf(“Arbitrary number is a root”);

Or, if you don't want to solve for all possible cases

 if (a != 0) {
   if (temp >= 0) {
     ...
   }
   else /* quadratic equation with complex roots only */
     printf(“There is no real value of roots of the given equation”);
 }
 else 
   printf(“The equation is not quadratic one”);  

Upvotes: 4

Peter
Peter

Reputation: 36597

Two obvious problems.

First

root1 = (-b + sqrt(temp))/a*2;

is equivalent, due to rules of operator precedence, to (note where I've added parentheses).

root1 = ((-b + sqrt(temp))/a)*2;

which is wrong. It should be something like

root1 = (-b + sqrt(temp))/(a*2) ;

A similar comment applies for the calculation of root2.

Second, the statement

printf(“Roots of the equation are %f and %f”, &root1,&root2); 

attempts to print the addresses of root1 and root2 (not the values of root1 and root2). That actually causes undefined behaviour. You need to remove the &s (which are required to use scanf() correctly, but not printf()).

There are some other flaws in your code (bad technique) but I won't deal with those.

Upvotes: 1

Related Questions