stensootla
stensootla

Reputation: 14875

making my C code shorter

I made a program that calculates the equation ( gives me the values x1 and x2 ). But the problem is though , i needed to write 2 seperate functions for x1 and x2 , even though i only needed to change a "+" sign to a "-" sign to get x2. Is it possible to get the same output put only using one function ? Heres the code :

double equation(double a, double b, double c) {
    double argument, x1;
    argument = sqrt(pow(b, 2) - 4*a*c);
    x1 = ( -b + argument ) / (2 * a);
    return x1;
}

double equation2(double a, double b, double c) {
    double argument, x2;
    argument = sqrt(pow(b, 2) - 4*a*c);
    x2 = ( -b - argument ) / (2 * a); // here i changed the "+" sign to "-"
    return x2;
}

Thank you in advance !

Upvotes: 3

Views: 158

Answers (3)

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

Pass in another argument that's either +1 or -1, and multiply argument by it. Or, pass in another argument that's either 0/false or non-0/true, and add or subtract conditionally (with an if statement or a ...?...:... "ternary operator".

[EDITED to remove a response to part of the original question that's now been removed.]

Upvotes: 3

Dan F
Dan F

Reputation: 17732

Theres a couple different ways you can do this. Gareth mentions one, but another is to use output parameters.

Using pointers as input parameters, you can populate them both in one function, and you don't need to return anything

void equation(double a, double b, double c, double *x1, double *x2) {
    double argument, x1;
    argument = sqrt(pow(b, 2) - 4*a*c);
    *x1 = ( -b + argument ) / (2 * a);
    *x2 = ( -b - argument ) / (2 * a);
}

Then call it from your main code:

int main (void )
{
    //Same up to the prints above
    double x1, x2;
    equation ( a , b, c , &x1, &x2);

    printf("\nx1 = %.2f", x1);
    printf("\nx2 = %.2f", x2);
}

Upvotes: 4

paxdiablo
paxdiablo

Reputation: 881973

Well, you could do something like:

double equation_either (double a, double b, double c, double d) {
    double argument, x1;
    argument = sqrt(pow(b, 2) - 4*a*c);
    x1 = ( -b + (d * argument)) / (2 * a);
    //          ^^^^^^^^^^^^^^
    // auto selection of correct sign here
    //
    return x1;
}
:
printf("\nx1 = %.2f", equation_either(a, b, c,  1.0));
printf("\nx2 = %.2f", equation_either(a, b, c, -1.0));

Upvotes: 1

Related Questions