Search code examples
cfunctionreturnreturn-value

How can I return 2 int values from a function


I need to return 2 values from 2 diffent functions. One of the values come from scanf(closedinterval()) and the other is made inside the function(rootinquad()). Is there a simple way to return these values?

#include <math.h>
#include <stdio.h>
int rootinquad()
{
    double a, b, c, discriminant, root1, root2, realPart, imagPart;
    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);
    discriminant = b * b - 4 * a * c;
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
    }
    else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
    }
    else {
        realPart = -b / (2 * a);
        imagPart = sqrt(-discriminant) / (2 * a);
    }
    return root1,root2;
} 
int closedinterval()
{
    int root1, root2,i=1;
    printf("Closed interval: ");
    scanf("%d%d", &root1, &root2);
    return root1,root2;
}
int main()
{
    int root1, root2;
    char ka;
    printf("Is there a closed interval in the question?(y/n) ");
    scanf(" %c", &ka);
    switch(ka)
    {
    case 'y':
    closedinterval();
    break;
    case 'n':
    rootinquad();
    break;
    default:
    printf("answer the question");
    break;
    }
    printf("%d%d",root1,root2);//test
    return 0;
}

I tried root1=closedinterval() but it works for only 1 value and I cant think of ways to return root2 without it being long and boring.


Solution

  • use a struct

    typedef struct roots {
        double root1, root2;
    } roots_t;
    
    roots_t solve(double a, double b, double c) {
        roots_t result;
        result.root1 = 0;
        result.root2 = 1;
        return result;
    }
    
    int main(int argc, char *argv[]) {
        roots_t s = solve(1,2,3);
        printf("result: %f %f", s.root1, s.root2);
        return 0;
    }