c++ - 从 1 个函数返回和输出 2 个整数

标签 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;
}

最佳答案

math 的返回类型是int ,这就是它返回的内容(一个整数)。

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

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

关于c++ - 从 1 个函数返回和输出 2 个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823417/

相关文章:

c++ - Windows 中 Paint 事件中的异常和访问冲突

c++ - 关于windows窗体中多线程和后台工作线程的一些问题

c++语句无效

c++ - 具有非阻塞输入的编辑行

python - 我们可以使用 SWIG 为 Qt 应用程序制作 python 绑定(bind)吗?

c++ - 如何将枚举值分配给用户定义的 double 变量?? C++

c++ - WIN32 多个窗口

c++ - 如何使 std::vector 类型安全

c++ - 基类对派生类指针的引用

c++ - 可以在 C++17 中模拟 C++2 0's ' operator==(const T&) = default' 吗?