如何从 C/C++ 函数中返回多个值?
在 C 或 C++ 中,我们无法直接从函数中返回多个值。在本节中,我们将了解如何使用某种技巧从函数中返回多个值。
我们可以使用“按址调用”或 按引用调用 方法从函数中返回多个值。在调用程序函数中,我们将使用两个变量来存储结果,而函数将采用指针类型数据。因此,我们必须传递数据的地址。
在本例中,我们将了解如何定义一个函数,该函数可以从一个函数中除以两个数字后的商和余数。
示例代码
#include<stdio.h>
void div(int a, int b, int *quotient, int *remainder) {
*quotient = a / b;
*remainder = a % b;
}
main() {
int a = 76, b = 10;
int q, r;
div(a, b, &q, &r);
printf("Quotient is: %d\nRemainder is: %d\n", q, r);
}
输出
Quotient is: 7 Remainder is: 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP