c语言有指针的原因二
#include <stdio> 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; int wa=0,sa=0; printf("请输入两个整数"); printf("整数A:"); scanf("%d",&na); printf("整数B:"); scanf("%d",&nb); sum_diff(na,nb,wa,sa); //调用后,这里的wa,sa被销毁,不复存在;另外函数返回值只能有一个,不能返回两个,所以函数返回值也解决不了 printf("%d,%d",wa,sa); //wa,sa的值都为0 return 0; }
#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; int *wa; int *sa; wa=(int *)malloc(sizeof(int)); sa=(int *)malloc(sizeof(int)); printf("请输入两个整数"); printf("整数A:"); scanf("%d",&na); printf("整数B:"); scanf("%d",&nb); sum_diff(na,nb,wa,sa); printf("%d,%d",*wa,*sa);
free(wa);
free(sa);
return 0; }