如何从函数返回 2 个 int 值

问题描述 投票:0回答:2

我需要从 2 个不同的函数返回 2 个值。其中一个值来自 scanf(closeinterval()),另一个值是在函数 (rootinquad()) 内部生成的。有没有简单的方法来返回这些值?

#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;
}

我尝试过 root1=closeinterval() 但它只适用于 1 个值,而且我想不出返回 root2 的方法,而不会让它又长又无聊。

c function return return-value
2个回答
0
投票

您可以通过地址传递变量来做到这一点:

#include <stdio.h>

void closedinterval(int *root1, int *root2)
{
    printf("Closed interval: ");
    scanf("%d%d", root1, root2);
}

int main()
{
    int root1, root2;

    closedinterval(&root1, &root2);

    printf("%d - %d",root1,root2);//test
    return 0;
}

0
投票

使用结构体

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.