c语⾔中利⽤函数同时返回两个数的和与差
c语⾔中利⽤函数同时返回两个数的和与差。
1、
#include <stdio.h>
void sum_diff(int n1, int n2, int sum, int diff)
{
sum = n1 + n2;
记住我diff = (n1 > n2) ? (n1 - n2) : (n2 - n1);
}
int main(void)
{
int na, nb, wa = 0, sa = 0;
puts("please input two integers.");
printf("na = "); scanf("%d", &na);
printf("nb = "); scanf("%d", &nb);
printf("wa: %d; sa: %d", wa, sa);
return0;
}
2、利⽤指针作为函数的参数。
#include <stdio.h>
int sum_dif(int n1, int n2, int *sum, int *dif) //⽣成的指针sum、和dif分别为指向wa和sa的指针,*sum和*dif分别相当于wa和sa的别名,对别名进⾏修改,相当于对wa和sa进⾏修改。{
*sum = n1 + n2;
*dif = (n1 > n2) ? (n1 - n2) : (n2 - n1);
}
int main(void)
{
int na, nb, wa = 0, sa = 0;
puts("please input two integers.");
printf("na = "); scanf("%d", &na);
printf("nb = "); scanf("%d", &nb);
sum_dif(na, nb, &wa, &sa); //指针作为实参传递给形参)
printf("\nwa: %d; sa: %d\n", wa, sa);
return0;
}
发布评论