从1个函数返回并输出2个整数

时间:2014-11-08 23:55:15

标签: c++

我必须编写一个代码,它有一个带两个整数的函数,并将x作为(a + b),y返回为(a * b),当我运行它时,它只输出y。为什么不输出(或返回)x?

#include <iostream>
using namespace std;

int math (int a, int b) {
    int x, y;

    x = a + b;
    y = a * b;

    return x, y;
}

int main() {

    cout << math (5,3);

    getchar();
    getchar();

    return 0;
}

4 个答案:

答案 0 :(得分:3)

math的返回类型是int,所以这是它返回的内容(单个整数)。

表达式x, y使用comma operator。逗号运算符计算x,丢弃其值,然后计算并返回y。换句话说,return x, y相当于return y

您可以使用std::pair<int,int>返回一对整数。

答案 1 :(得分:1)

该行

return x, y;

不符合您的期望。 comma operator仅返回最后一个逗号后的值 - 在本例中为y。要返回多个值,您应使用struct或包含两者的类。

答案 2 :(得分:0)

你只能归还一件事。您可以将它们放在结构中,然后返回它。更简单的例子。

struct xy {
    int x;
    int y;
};

xy math(int a, int b) {
    xy pair;
    int x, y;
    pair.x = a + b;
    pair.y = a * b;    
    return pair;
}

答案 3 :(得分:0)

有两种方法可以使函数返回多个值。该 首先是使用参数,引用或指针:

void
math( int a, int b, int& sum, int& product )
{
    sum = a + b;
    product = a * b;
}

int
main()
{
    int s;
    int p;
    math(5, 3, s, p);
    std::cout << s << ' ' << p << std::endl;
    return 0;
}

另一种是定义一个包含两个值的类:

struct MathResults
{
    int sum;
    int product;
};

MathResults
math( int a, int b )
{
    return MathResults{ a + b, a * b };
}

std::ostream&
operator<<( std::ostream& dest, MathResults const& value )
{
    dest << value.sum << ' ' << value.product;
}

int
main()
{
    std::cout << math( 5, 3 ) << std::endl;
    return 0;
}

在大多数情况下,第二种解决方案是首选。