函数参数中可以设置输出的参数,这里就不用写return了,并且在调用函数时,可以更新当前的数据规则,使得程序继续向前执行(冒泡排序就是这种特定,感兴趣可以观看:
C语言使用技巧(十二):如何找到冒泡排序之后最小数值在原数组中的索引),我们可以先来看看一个交换函数的例子:
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
int main()
{
int a = 10;
int b = 20;
printf("the value of a is %d,b is %d\n", a, b);
swap(&a, &b);
printf("After swap,the value of a is %d,b is %d\n", a, b);
system("pause");
return 0;
}
执行结果:
稍微修改一下输出的参数, 和函数的摆动值:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void swap(int *a, int *b, double *sum)
{
int c;
c = *a;
*a = *b;
*b = c;
*sum = *a + *b + tan(*a / (2*(*b)));
}
int main()
{
int a = 10;
int b = 20;
double sum = 0;//记得给一个初值
printf("the value of a is %d,b is %d\n", a, b);
swap(&a, &b, &sum);
printf("After swap,the value of a is %d,b is %d\n", a, b);
printf("sum = %lf\n", sum);
system("pause");
return 0;
}
执行结果:
应用于布尔类型:
if(ret)传进来的第一个判断默认为真
if(!ret) 否则取反
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define bool bool
#define true 1
#define false 0
void swap(int *a, int *b, double *sum)
{
int c;
c = *a;
*a = *b;
*b = c;
*sum = *a + *b + tan(*a / (2 * (*b)));
}
//布尔函数
bool fun(int *a, int *b, double *sum)
{
if (*sum > *a + *b)
{
return true;
}
else
{
return false;
}
}
int main()
{
int a = 10;
int b = 20;
double sum = 0; //记得给一个初值
printf("the value of a is %d,b is %d\n", a, b);
swap(&a, &b, &sum);
printf("After swap,the value of a is %d,b is %d\n", a, b);
printf("sum = %lf\n", sum);
bool ret;
ret = fun(&a, &b, &sum);
if(ret)
{
printf("偏差为正\n");
}
else
{
printf("偏差为负\n");
}
system("pause");
return 0;
}
该函数最终结果是ret为正的数。
执行结果:
偏差为正
改成!ret
执行结果:
偏差为负