在同一个函数中返回多个变量

时间:2018-03-07 00:29:20

标签: c

我只需要帮助使用相同的函数返回两个用户输入浮点数。谁能告诉我如何返回多个变量?提前谢谢。

#include <stdio.h>

#define SIDE_1_LABEL 'A'
#define SIDE_2_LABEL 'B'

float getUserValue(float side1, float side2);

int main()
{
    float   side1,
            side2; 

    side1     = getUserValue(SIDE_1_LABEL);
    side2     = getUserValue(SIDE_2_LABEL);

    return 0;
}

float getUserValue(float side1, float side2)
{      
    printf(" Enter a value for Side %c.\n", SIDE_1_LABEL);
    printf("> ");

    scanf("%f", &side1); 

    printf(" Enter a value for Side %c.\n", SIDE_2_LABEL);
    printf("> ");

    scanf("%f", &side2);

    return side1, side2;
}

1 个答案:

答案 0 :(得分:2)

您需要将两个浮点数放入函数可以返回的结构中,或者将一个(或两个)浮点数作为pass-by-reference参数传递。在这种情况下,我肯定更喜欢两个pass-by-reference参数。

void getUserValue(float *side1, float *side2) {      
    printf(" Enter a value for Side %c.\n", SIDE_1_LABEL);
    printf("> ");

    scanf("%f", side1); 

    printf(" Enter a value for Side %c.\n", SIDE_2_LABEL);
    printf("> ");

    scanf("%f", side2);
}

您的代码中还有其他严重问题,例如将字符AB作为getUserValue()的浮点参数传递,并且每次调用只传递一个。您应该将getUserValue()称为:

int main() {
    float   side1, side2; 

    getUserValue(&side1, &side2);

    return 0;
}

您无需传入SIDE_1_LABELSIDE_2_LABEL,因为它们是全局#defined,可以由getUserValue()直接访问。由于您在一次通话中同时获得两个值,因此无需再拨打getUserValue()两次。

另一种方法是让getUserValue()一次只获得一个值:

float getUserValue(char label) {
    float side;

    printf(" Enter a value for Side %c.\n", label);
    printf("> ");

    scanf("%f", &side);

    return side;
}

然后像你现在这样打电话两次:

side1     = getUserValue(SIDE_1_LABEL);
side2     = getUserValue(SIDE_2_LABEL);
相关问题