【函数传值】
向函数传值是函数间传递数据的基本方式,简称传值方式。实质是调用函数把实参的值复制了一份传给了被调用函数的形参,使形参获得了初始值,无副作用。
【函数传址】
函数传址是函数间传递数据的又一种方式,简称传址方式。实质是调用函数把一个或多个内存地址传递给被调函数的形参,使形参指向了内存中的指定位置,有副作用。
以下例子运用了函数传值和传址的方式进行函数调用解出了一元二次方程:
//解一元二次方程ax^2+bx+c=0,练习函数调用,传值和传址的理解
#include<stdio.h>
#include<math.h>
//函数声明
void getdata (int *a,int*b, int *c);
int quadratic(int a,int b,int c, double *proot1, double*proot2);
void printresults(int numberroots, int a,int b,int c,double root1, double root2);
//主程序
int main()
{
int a,b,c,numberroots;
double root1,root2;
char again='Y';
printf("solve quadratic equations \n\n");
while(again=='Y'||again=='y') /*可保证继续输入然后继续计算*/
{
getdata(&a,&b,&c);/*作用是输入三个变量的值,用函数传址的办法*/
numberroots=quadratic(a,b,c,&root1,&root2);/*计算函数*/
printresults(numberroots,a,b,c,root1,root2);/*输出函数*/
getchar ();
printf("\n do you have another equation (Y/N):");
scanf("%c",&again);
}
printf("\n thank you.\n");
return 0;
}
//getdata函数定义
void getdata(int *pa,int *pb,int *pc)
{
printf("piease enter coefficiences a,b and c;");
scanf("%d %d %d",pa,pb,pc);
return;
}
//quadratic函数定义,主要求解过程
int quadratic(int a, int b, int c, double *proot1, double *proot2)
{
int result;
double discriminant;
double root;
if(a==0&&b==0)
{result=-1;}
else if(a==0)
{*proot1=-c/(double)b;
result=1;
}
else
{
discriminant=b*b-(4*a*c);
if(discriminant>=0)
{
root=sqrt(discriminant);
*proot1=(-b+root)/(2*a);
*proot2=(-b-root)/(2*a);
result=2;
}
else
result=0;
}
return result;/*返回解的个数*/
}
//printresult函数定义
void printresults(int numberroots,int a,int b,int c, double root1, double root2)
{
printf ("your equation : %dx^2+%dx+%d\n",a,b,c);
switch(numberroots)
{
case 2:printf("roots are :%6.3f %6.3f\n",root1,root2);
break;
case 1:printf("only one root :%6.3f\n",root1);
break;
case 0:printf("roots are imaginary.\n");
break;
default :printf("invalid cofficients\n");
break;
}
return;
}