Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to write a programm which calculates the x1 and x2 of a quadratic equation.

What I have tried:

C++
#include <stdio.h>
#include <stdlib.h>

int main()
{
printf("ax^2+bx+c\n\n");
    int a, b, c;
    printf("enter integer a\n");
    scanf("%d", &a);
    printf("enter integer b\n");
    scanf("%d", &b);
    printf("enter integer c\n");
    scanf("%d", &c);

printf("x1=%d, x2=%d",(-b+(b*b-4*a*c)^0.5)/2*a, (-b-(b*b-4*a*c)^0.5)/2*a);




    return 0;
}
Posted
Updated 12-Oct-20 22:50pm
v2

The '^' operator in the C language is the binary exclusive or. It is NOT exponentiation.
 
Share this answer
 
Comments
CPallini 13-Oct-20 4:08am    
5.
Maciej Los 13-Oct-20 4:30am    
5ed!
 
Share this answer
 
Comments
CPallini 13-Oct-20 4:08am    
5.
Richard MacCutchan 13-Oct-20 4:20am    
:thumbsup:
Maciej Los 13-Oct-20 4:30am    
5ed!
Just use the sqrt function to calculate the square root.
 
Share this answer
 
Comments
CPallini 13-Oct-20 4:51am    
5. Indeed.
Shao Voon Wong 13-Oct-20 5:49am    
Thanks!
To elaborate Rick and Richard solution, try
C
#include <stdio.h>
#include <math.h>

int main()
{
    printf("ax^2+bx+c\n\n");
    int a, b, c;
    printf("enter integer a\n");
    scanf("%d", &a);
    printf("enter integer b\n");
    scanf("%d", &b);
    printf("enter integer c\n");
    scanf("%d", &c);
    double d = b * b - 4 * a * c;
    if ( b < 0)
    {
      //TODO: show here the complex solutions 

    }
    else
    {
      d = sqrt(d);
      double x1, x2;
      x1 = (- b + d)/2/a;
      x2 = (- b - d)/2/a;
      printf("x1=%g, x2=%g\n", x1, x2);
    }
    return 0;
}


Please note:
  • You have to include the <math.h> header (and possibly link with the math library)
  • You don't actually need the pow function, the sqrt function is just enough
  • In order to divide something by 2a, you must write either
    something/2/a
    or
    something/(2*a)
    (writing,as you did, something/2*a is plain wrong).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900