本文摘自PHP中文网,作者青灯夜游,侵删。
有时我们需要从通过一个函数返回多个值,不幸的是C/C ++不允许这样做;但我们可以通过一些巧妙的方法来达到这种效果。下面本篇文章就来给大家介绍C/C++从函数中返回多个值的方法,希望对大家有所帮助。【视频教程推荐:C语言教程、C++教程】
方法一:通过使用指针:
在函数调用时,传递带有地址的参数,并使用指针更改其值;这样,修改后的值就会变成原始参数。
下面通过代码示例来看看如何实现。
示例:输入2个数,比较大小后重新输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # include <stdio.h>
void compare(int a, int b, int* add_great, int* add_small)
{
if (a > b) {
*add_great = a;
*add_small = b;
}
else {
*add_great = b;
*add_small = a;
}
}
int main()
{
int great, small, x, y;
printf( "输入两个数字: \n" );
scanf( "%d%d" , &x, &y);
compare(x, y, &great, &small);
printf( "\n最大值为:%d,最小值为:%d" ,
great, small);
return 0;
}
|
输出:

方法二:通过使用结构
因为结构是用户定义的数据类型;我们可以定义一个包含两个整数变量的结构,并将更大和更小的值存储到这些变量中,然后使用该结构的值。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # include <stdio.h>
struct greaterSmaller {
int greater, smaller;
};
typedef struct greaterSmaller Struct;
Struct findGreaterSmaller(int a, int b)
{
Struct s;
if (a > b) {
s.greater = a;
s.smaller = b;
}
else {
s.greater = b;
s.smaller = a;
}
return s;
}
int main()
{
int x, y;
Struct result;
printf( "输入两个数字: \n" );
scanf( "%d%d" , &x, &y);
result = findGreaterSmaller(x, y);
printf( "\n最大值为:%d,最小值为:%d" ,
result.greater, result.smaller);
return 0;
}
|
输出:

方法三:通过使用数组
当一个数组作为参数传递时,它的基地址将传递给该函数,因此无论对数组副本所做的任何更改,它都会更改为原始数组。
注:该方法仅当返回的项具有相同类型时才可以工作。
示例:使用数组返回多个值,会在arr [0]处存储更大的值,在arr [1]处存储更小的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # include <stdio.h>
void findGreaterSmaller(int a, int b, int arr[])
{
if (a > b) {
arr[0] = a;
arr[1] = b;
}
else {
arr[0] = b;
arr[1] = a;
}
}
int main()
{
int x, y;
int arr[2];
printf( "输入两个数字: \n" );
scanf( "%d%d" , &x, &y);
findGreaterSmaller(x, y, arr);
printf( "\n最大值为:%d,最小值为:%d" ,
arr[0], arr[1]);
return 0;
}
|
输出:

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!
以上就是C/C++函数如何返回多个值?(代码示例)的详细内容!
相关阅读 >>
c#调用c++ 动态链接库dll
c 语言结构体详解
c++ 判断本机是否有.net环境
第一章c++:函数返回值、gnu编译器命令
devc++怎么调背景
c++ 图解层序遍历和逐层打印智能指针建造的二叉树
c语言中&是什么意思?
技术解答面向对象的初步认识(c++ 类)
c++实现在二维数组中的查找
c++是一种高级程序设计语言吗?
更多相关阅读请进入《c》频道 >>
转载请注明出处:木庄网络博客 » C/C++函数如何返回多个值?(代码示例)