Question

Whenever I try running this, it returns the wrong solution, for example:
A: 303
B: 405
C: 50

Real solution: −0.13762776465722773
My solution : -110079.531250

#include <stdio.h>
#include <math.h>
int main(){
    float a;
    float b;
    float c;
    float solution;
    float d;
    printf("A: ");
    scanf("%f", &a);
    printf("B: ");
    scanf("%f", &b);
    printf("C: ");
    scanf("%f",&c);
    d = b * b - 4 * a * c;
    solution = (-b - sqrt(d))/ 2*a;
    printf("%f", solution);
}
Was it helpful?

Solution

You forgot BODMAS. Replace (-b - sqrt(d))/ 2*a by (-b - sqrt(d))/ (2*a)

OTHER TIPS

solution = (-b - sqrt(d))/ (2*a);

Two things.

You need to watch out for the order of operations.

solution = (-b - sqrt(d)) / (2*a);

And depending on your customer you need to consider the accuracy of your result. See "Avoiding loss of significance" for more information

And finally - i had a bit of fun writing my own version of your program:

#include <stdio.h>
#include <math.h>

void printLineSolution( double a, double b, double c );

int main()
{
    printLineSolution(303,405,50);
    printLineSolution(1,2,0);
    printLineSolution(1,2,-1);
    printLineSolution(1,-2,-3);
    printLineSolution(1,-6,9);
    printLineSolution(1,3,3);
    getchar();
}

void printLineSolution( double a, double b, double c )
{
    double d = (b * b) - (4 * a * c);
    printf("(%lg)x^2 + (%lg)x + (%lg) = 0 ", a, b, c);
    if( a == 0 )
    {
        printf("=> not quadratic");
    }
    else
    {

        if( 0 > d )
        {
            double r = - b / (2*a);
            double i = sqrt( -d ) / (2*a);
            printf("=> 2 complex: %lg + %lgi ; %lg - %lgi", r, i, r, i);
        }
        else if ( 0 == d )
        {
            double solution = - b / (2*a);
            printf("=> 1 real: %lg", solution);
        }
        else
        {
            double s1 = (- b + sqrt( d ) ) / (2*a);
            double s2 = (- b - sqrt( d ) ) / (2*a);
            printf("=> 2 real: %lg ; %lg", s1, s2);
        }
    }
    printf("\n");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top